Как прочитать обновленное состояние в приложенииact-redux? - PullRequest
0 голосов
/ 22 марта 2019

Я изучаю Redux и пытаюсь добавлять / просматривать пользователей с помощью приставки в моем приложении реакции. Используя «ref» в реакции, я читаю полезную нагрузку (name, 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 в моем создателе действий, но я получаю 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

Ответы [ 4 ]

1 голос
/ 22 марта 2019
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 голос
/ 22 марта 2019

Реагирующие ссылки дают вам ссылку на элемент 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

0 голосов
/ 22 марта 2019
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
    }
}
0 голосов
/ 22 марта 2019

Вы назначаете элемент в переменную во время события onclick.

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...