【问题标题】:Reactjs Get the stored value from a store through reduxReactjs 通过 redux 从 store 中获取存储的值
【发布时间】:2018-10-29 12:41:56
【问题描述】:

我想保存我通过 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;

【问题讨论】:

  • 没有得到你关于对象/数组的问题,但已经回答了你的主要问题

标签: reactjs redux


【解决方案1】:

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

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

connect(mapStateToProps)(AnotherComponent);

现在AnotherComponent 将收到userName 作为道具:

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

【讨论】:

  • 感谢您对 mapStateToProps 的解释!不要担心第二个问题。它来自缺乏基本的编程知识。要努力学习。哈哈祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
相关资源
最近更新 更多