简体   繁体   English

如何从Redux存储中获取最新值到状态?

[英]How to get the latest value to a state from a redux store?

I am fairly new to Redux, I'm using the react-redux package and trying to implement a simple feature (although I know this can be handled via local state), where whatever you type in the input should be displayed below between the <p></p> tags. 我对Redux相当陌生,我使用react-redux软件包并尝试实现一个简单的功能(尽管我知道这可以通过本地状态来处理),在此输入的内容应在<p></p>标签。

Below is the code: 下面是代码:

编辑73zq1yl2r1

I'm a bit skeptical about line 62, the way I am accessing the latest state to print out, is it the correct way? 我对第62行表示怀疑,这是我访问最新状态以进行打印的方式,这是正确的方法吗?

Good Start by the way. 好的开始。 I think you have little bit complicated the state part. 我认为您在状态部分有些复杂。 I modified it for you and also removed bind keyword which i feel not required if you use latest JS lang spec. 我为您修改了它,还删除了bind关键字,如果您使用最新的JS lang规范,我觉得不需要。

I have used Object.assign just to prevent the state object mutation. 我使用Object.assign只是为了防止状态对象发生突变。 Usually this is avoided by using ImmutableJS (Please read the doc) 通常可以通过使用ImmutableJS来避免这种情况(请阅读文档)

// Reducer.
const updateReducer = (state = {text:''}, action) => {
  switch (action.type) {
    case UPDATE_TEXT:
      return Object.assign({}, state, { text: action.text });
    default:
      return state;
  }
};

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

And Render method: 和渲染方法:

 render() {
    return (
      <div>
        <input type="text" onChange={(...arg) => this.changeText(...arg)} />
        <p>{this.props.text}</p>
      </div>
    );
  }

Whats wrong with your initial code? 您的初始代码有什么问题?

You were storing all the text in an array for each key stroke alongside with updated and growing text. 您将每个按键的所有文本以及更新和增长的文本存储在数组中。 At render just display the last one (Created unwanted copies in the array which is never used) and omit other array values. 在渲染时,仅显示最后一个(在数组中创建了不需要的副本,这些副本从未使用过),并省略了其他数组值。 Instead just replace the old value with current incoming value. 相反,只需将旧值替换为当前输入值即可。

Your Forked code here 您的分叉代码在这里

Happy Coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM