如何使用 Flux Stores 更改对象值?
How do you change Object values with Flux Stores?
自从 Facebook removed Flux's MapStore 以来,我很难找出在其商店中改变对象的最佳方法。
ReduceStore 应该能够处理这个问题,Cássio de Sousa Antonio 的 Pro-React 书中有几个 ReduceStore 的例子,但是 none 其中强调了这个功能,我是有点丢失。
class MyObjectStore extends Flux.ReduceStore {
getInitialState(){
return {
foo: '',
bar: '',
baz:''
};
}
reduce(state, action){
switch (action.type) {
case constants.CHANGE_FOO:
return state.set('foo', action.value)
case constants.CHANGE_BAR:
return state.set('bar', action.value)
case constants.CHANGE_BAZ:
return state.set('baz', action.value)
default:
return state;
}
}
}
export default new MyObjectStore(AppDispatcher);
// => TypeError: state.set is not a function
我试过:
state.foo = action.value;
return state;
但这样做不会触发任何更改。
更新:
使用不可变有效:
import Immutable, {Map} from 'immutable';
class MyStore extends ReduceStore {
getInitialState(){
return Map({
foo: '',
bar: '',
baz: ''
});
}
reduce(state, action){
switch (action.type) {
case constants.CHANGE_FOO:
return state.set('foo', action.value)
case constants.CHANGE_BAR:
return state.set('bar', action.value)
case constants.CHANGE_BAZ:
return state.set('baz', action.value)
default:
return state;
}
}
}
但是,现在在渲染方法中,我必须小心使用地图的getter功能,例如:
const bar = this.props.foo.get('bar');
您的初始状态是一个普通对象,但您的 reduce
似乎在对不可变对象进行操作。这意味着当第一次调用 reduce
时,state
是一个没有 set
属性 的普通对象,给你你提到的 TypeError。将您的 getInitialState
更改为 return 一个不可变的映射(例如,包装您在 Map(...)
中的内容)将修复它。
自从 Facebook removed Flux's MapStore 以来,我很难找出在其商店中改变对象的最佳方法。
ReduceStore 应该能够处理这个问题,Cássio de Sousa Antonio 的 Pro-React 书中有几个 ReduceStore 的例子,但是 none 其中强调了这个功能,我是有点丢失。
class MyObjectStore extends Flux.ReduceStore {
getInitialState(){
return {
foo: '',
bar: '',
baz:''
};
}
reduce(state, action){
switch (action.type) {
case constants.CHANGE_FOO:
return state.set('foo', action.value)
case constants.CHANGE_BAR:
return state.set('bar', action.value)
case constants.CHANGE_BAZ:
return state.set('baz', action.value)
default:
return state;
}
}
}
export default new MyObjectStore(AppDispatcher);
// => TypeError: state.set is not a function
我试过:
state.foo = action.value;
return state;
但这样做不会触发任何更改。
更新:
使用不可变有效:
import Immutable, {Map} from 'immutable';
class MyStore extends ReduceStore {
getInitialState(){
return Map({
foo: '',
bar: '',
baz: ''
});
}
reduce(state, action){
switch (action.type) {
case constants.CHANGE_FOO:
return state.set('foo', action.value)
case constants.CHANGE_BAR:
return state.set('bar', action.value)
case constants.CHANGE_BAZ:
return state.set('baz', action.value)
default:
return state;
}
}
}
但是,现在在渲染方法中,我必须小心使用地图的getter功能,例如:
const bar = this.props.foo.get('bar');
您的初始状态是一个普通对象,但您的 reduce
似乎在对不可变对象进行操作。这意味着当第一次调用 reduce
时,state
是一个没有 set
属性 的普通对象,给你你提到的 TypeError。将您的 getInitialState
更改为 return 一个不可变的映射(例如,包装您在 Map(...)
中的内容)将修复它。