简体   繁体   中英

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.

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?

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.

I have used Object.assign just to prevent the state object mutation. Usually this is avoided by using ImmutableJS (Please read the doc)

// 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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