简体   繁体   中英

React redux store vs component state

I have a component with an input element. Onchange, I want to update the Redux store and local state, because I render {this.state.inputValue} in the component.

The reason I need for it to be in the Redux store, is that the user could hit save button (which is on a different component) at anytime.

I can't think of any other way to keep local state, and allow a 'Save' to access the data. But it seems like this approach breaks the 'single source of truth' rule. What is the right way to do this? Thanks.

Here is a way to solve the problem. The solution assumes that the InputFormComponent and the ActionComponent are within some ParentComponent or can easily be wrapped in one.

The ParentComponent is wrapped with connect and has access to redux store. The Parent's render on an abstract level looks like this (there could be any level of siblings or nesting):

//Parent Component
render() {
    return (
        <InputFormComponent
            data={this.{state|prop}.initialData}
            userClickedSave={this.state.userClickedSave}
            clickSavedAcknowledged={this.clickedSavedAcknowledged}
        />

        <ActionComponent
            onSaveClicked={this.onSaveClicked}
        />
    )
}

From the above code we can understand that the ParentComponent has a userClickedSave flag on its state . It has a method called onSaveClicked which when called from the ActionComponent will update this.state.userClickedSave to true .

Now lets see how InputFormComponent will behave to userClickedSave on its componentWillReceiveProps :

//Input form component
componentWillReceiveProps(nextProps) {
    if (nextProps.userClickedSave && this.props.userClickedSave !== nextProps.userClickedSave) {
        nextProps.clickSavedAcknowledged(this.state.inputValue)
    }
}

The InputFormComponent will listen for userClickedSave changes and for correct scenario, it will call clickSavedAcknowledged with the current input value, which the ParentComponent can now save to the redux store:

//Parent component
clickSavedAcknowledged(inputValue) {
    this.props.saveInputValue(inputValue)

    this.setState({
        userClickedSave: false
    })
}

onSaveClicked() {
    this.setState({
        userClickedSave: true
    })
}

As you can see the Parent saves data to redux store and also reset userClickedSave back to false , so the process can repeat when the user click the save button.

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