简体   繁体   中英

using local state for input value with redux store

i started learning redux and i've got the following question. so I have a redux store with initial state and i also have a component which is responsible (dispatching an action) with user inputted data. so if the inputs are controlled should i set their value property in redux store (initalState) and dispatch an action every time value changes or should i use local state of component -

 class Calc ...
   constructor(props){
       super(props);
       this.handleChange = this.handleChange.bind(this);
       this.state = {
           inputVal: ''
       }
   }

   handleChange(e){
      this.setState({
         [e.target.name]: e.target.value
      })
   }

   render(){
     return(
          <div>
              <input type="text" name="inputVal" value={this.state.inputVal} onChange={this.handleChange} />
          </div>
     )
   }

in my opinion, before you store something in redux store, you should ask yourself some questions:

  • if my state "inputVal" will be shared between the other components?
  • if the change of my "inputVal" have some impacts on the other components

If you get the absolute answer "YES", you might need to store this state "inputVal" in redux state.

If NO, you do NOT need to store this state in redux. Instead of it, just handle the state within your component "Cal"

When a component is connected to Redux store it gets notified about the changes done to the store.

Therefore if
- two or more components would benefit from being notified about the state changes and
- these components are not in parent-child type of relationship when it's very easy for typically the parent to be aware about the changes related to self and the child and then let the child know what it should do by changing its props

then use Redux store.

Additionally there might be entirely different situation when just one single (or maybe several) component(s) need to be notified about navigation changes eg user using Back/Foward browser buttons. In such case use Redux as well, in conjuction with Router that automatically dispathes an action to Redux store with relevant payload.

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