react-redux: What is the difference between state.

2020-08-09 11:25发布

问题:

I've seen the use of setInt() and set() in some react-redux code:

state.setIn(...);
state.set(...);

I've found some documentation here https://facebook.github.io/immutable-js/ But unfortunately the method is not documented in detail.

I also found some other questions: Using React's immutable helper with Immutable.js But these do not answer my question.

I understand, that it must do some immutable stuff? But what's the immutable thing here? And what's the difference between set() and setIn()? Why do we need immutable?

回答1:

Immutable set method only sets immediate properties, I.e. direct children of the object. A setIn let's you set the value of any deep node down the data. set only takes property name. setIn takes an array of keys/index to reach down to the deeply nested element.

var basket = Immutable.Map({"milk":"yes", "flour":"no"});

basket = basket.set("flour", "yes");

basket = Immutable.Map({"fruits":{"oranges":"no"}, "flour":"no"});

basket = basket.setIn(["fruits", "oranges"], "yes");

The getIn/setIn methods are extremely useful when updating states in stores as you can use generic actions and supply the key paths to child components. They can invoke the actions passing the paths as parameters.



回答2:

set and setIn are one of the immutablejs method which you use to set data in a list or map object. simple example to understand this is lets say you have a this

//note that fromJS is another method which comes from immutablejs library

const iniState = fromJS({
    name:null,
    friends:fromJS({
       name:null
    }),
})

in this case you need to update the initial state with the latest then that's where you can use set and setIn methods.

iniState.set('name',"sibusiso Massango").setIn(['friends','name'],"Zweli Mathebula");

this is how you can use the set and setIn method, to find more about this you can read this docs https://facebook.github.io/immutable-js/docs/