Reactjs通过Redux从商店获取存储的值

时间:2018-10-29 12:41:56

标签: reactjs redux

我想保存通过redux键入并提交的值,并在另一个组件上获取该值。在这种情况下我该怎么办?

plus如果您解释它何时是一个对象或何时是一个数组,将不胜感激。谢谢!

// AddName.js
state = {
   user: ''
}

handleChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState(
        { [name]: value }
    );
}

handleSubmit = (e) => {
   const userName = this.state.user;
   const name = {
       userName: userName
   }
   this.props.dispatch({
       type: 'ADD_NAME'
       userName
   })
}

<form onSubmit={this.handleSubmit}>
   <input
      onChange={this.handleChange}
      name="user"
      value={this.state.user}
   />
</form>

export default connect()(AddName);

// addNameReducer.js
const addName = (state = {}, action) => {
switch(action.type) {
    case 'ADD_NAME':
        console.log("add_name");
        return { userName: action.userName };
    default:
        return state;
   }
 }

 export default addName;

//anotherComponent.js
<p> {I want the stored value here } </p>
export default anotherComponent;

1 个答案:

答案 0 :(得分:0)

您需要使用connect()软件包中的react-redux函数将组件连接到redux存储。它接受mapStateToProps函数作为第一个参数,该参数用于将值从存储传递到组件:

const mapStateToProps = state => ({
  userName = state.userName
});

connect(mapStateToProps)(AnotherComponent);

现在AnotherComponent将获得userName作为道具:

export default const AnotherComponent = props => <p>{props.userName}</p>