Как прочитать обновленное состояние в приложении react-redux?

#reactjs #react-redux

#reactjs #react-redux

Вопрос:

Я изучаю Redux и пытаюсь добавлять / просматривать пользователей с помощью redux в моем приложении react.Используя ‘ref’ в react, я считываю полезную нагрузку (имя, account_number) нового пользователя и передаю создателю действия ‘addProfile’ при нажатии кнопки ‘Добавить’ таким образом —

AddView.js

 import React from 'react';
import { connect } from 'react-redux';

import { addProfile } from '../actions';

class AddView extends React.Component{

    addValues(){
        return(
            <div>
                Name : <input type="text" value={this.props.profiles.name} ref={el => this.nameValue=el}/> 
                Account Number : <input type="text" value={this.props.profiles.account_number} ref={el => this.accountValue=el}/>
                <button onClick={() => this.props.addProfile(this.nameValue,this.accountValue)}>Add</button>

            </div>
        );
    }
    render(){

        return (
            <div>
                Add Profile
                <br /><br />
                {this.addValues()}

            </div>
        );
    }

}
const mapStateToProps = (state) => {
    return { profiles : state.profiles }
}
export default connect(mapStateToProps, {addProfile}) (AddView);
  

Теперь я пытаюсь записать в консоль имя, account_number в моем action creator, но вместо значений я получаю html.

 export const addProfile = (name, account_number) => {
    console.log(name,account_number)
    return{
        type :'ADD_PROFILE',
        payload : {
            name : name,
            account_number : account_number
        }
    };
}
  

Кто-нибудь, пожалуйста, может помочь, где я ошибся. Полный код здесь — https://codesandbox.io/s/239j97y36p

Комментарии:

1. если это только для отладки, почему бы не использовать redux-dev-tools-extension , у вас был бы пользовательский интерфейс nive с тестовыми примерами, историей и многими другими функциями

Ответ №1:

Ссылки React дают вам ссылку на элемент dom, если вам просто нужно значение входных данных, с помощью которого вы можете его получить .value . Я бы также переименовал ваши переменные ref, чтобы они были точными, как nameInputRef и accountInputRef .

     Name :{" "}
    <input
      type="text"
      value={this.props.profiles.name}
      ref={el => (this.nameInputRef = el)}
    />
    Account Number :{" "}
    <input
      type="text"
      value={this.props.profiles.account_number}
      ref={el => (this.accountInputRef = el)}
    />
    <button
      onClick={() =>
        this.props.addProfile(this.nameInputRef.value, this.accountNumberRef.value)
      }
    > Add
    </button>
  

Вы можете увидеть полный пример, адаптированный из вашего, здесь:https://codesandbox.io/s/k3mp28lr3o

Ответ №2:

 class UserProfile extends Component {
    constructor(props) {}
    render() {

        // ref={el => this.nameValue=el} to access input variable 
        // or 
        // use onChange event which fire another dispatcher which mutate profile state since we assign input values to profile state you can use state to get latest values


        //this.props.profiles
        //this.props.onAddProfile()
    }
}

const mapStateToProps = state => {
  return {
    profiles : state.profiles
  }
}

const mapDispatchToProps = dispatch => {
  return {
      onAddProfile:dispatch(addProfile())
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(UserProfile);
  

Комментарии:

1. addProfile должен возвращать ваш объект action.

2. нужен пример, пожалуйста, дайте мне знать. будет обновляться с примером 🙂

3. Да, пожалуйста .. Я не уверен, как использовать mapDispatchToProps, поэтому, пожалуйста, объясните обработку события с помощью примера кода

Ответ №3:

Вы присваиваете элемент переменной во время события onclick.

 ref={el => this.nameValue=el}
  

Вы можете использовать локальное состояние для хранения значения while onChange вместо ref

Ответ №4:

 npm install redux-thunk --save
  

profile.jsx

 class Profile extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
                <input
                    type="text"
                    onChange={({ target }) =>
                        this.props.onUsernameUpdated(target.value)
                    }
                    value={this.props.profile.username}
                    placeholder="Username"
                />

                <input
                    type="text"
                    onChange={({ target }) =>
                        this.props.onAccNumberUpdated(target.value)
                    }
                    value={this.props.profile.accNumber}
                    placeholder="Account Number"
                />

                <button onclick={this.props.onUpdateProfile}>Submit</button>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        profile: state.profile
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onUsernameUpdated: username => dispatch(usernameUpdated(username)),
        onAccNumberUpdated: password => dispatch(accNumberUpdated(accNumber)),
        onUpdateProfile: () => dispatch(updateProfile())
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Profile);
  

actions.js

 export function usernameUpdated(username) { // need reducer to update state profile name
    return {
        type: 'USER_NAME_UPDATE',
        data: username
    }
}

export function accNumberUpdated(accNumber) { // need reducer to update state profile acc number
    return {
        type: 'ACC_NUM_UPDATE',
        data: accNumber
    }
}

export function updateProfile() {
    return (dispatch, getState) => { //thunk magic
        // latest profile after user input
        const profile = getState().profile
    }
}