Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

reactjs - Redux store updates everything even if I just update a nested attribute?

In my application, the user should have the possibility to edit his name. I thought about having his initial name as the default value of useState(). This works perfectly - the name is also updated as well.

function EditName(props) {
    const { navigation, dispatch, initFirstName } = props;

    const [text, setText] = useState(initFirstName);

    return (
      <>
        <Button title="Save" onPress={() => dispatch(updateFirstName(text))} />
        <TextInput
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={(inp) => setText(inp)}
          value={text}
        />
      </>

    )


}

function mapStateToProps(state) {
  return (
    {
      initFirstName: state.user.data.firstName,
    }
  );
}

export default connect(mapStateToProps)(EditName);

But now I came across a problem if the user clicks on the save button and dispatch(updateFirstName(text)) is handled. text is overwriten by initFirstName again.

My Redux (toolkit) store is structured as follows:

{
  data: {
    firstName: "Test"
  },
  updateFirstName: {
   pending: null,
   error: null,
  },    
}

The updateFirstName(text) method dispatches an action that sets state.updateFirstName.pending = true;. If I leave this out - everything works.

So I guess that a new reference to the store (state) is created and React thinks: "Oh - I got a new initFirstName" (beside it's still the same because the update hasn't happened yet).

What would be a better way to do this? What's a solution for this problem?

question from:https://stackoverflow.com/questions/65870537/redux-store-updates-everything-even-if-i-just-update-a-nested-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe try to create a function that will be called instead of assigning onPress an arrow function. Basically, the function will be called with the initial value of text.

Make sure you use the current value of text, try this:

const saveHandler = () => {
    dispatch(updateFirstName(text))
}
...
<Button title="Save" onPress={saveHandler} />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...