我试图用从商店收到的新道具重新修改我的反应性组件,但是道具似乎没有得到更新。这种方法通常对我有效,只是在这种情况下它不起作用。
组件
class Cart extends React.Component {
static getStores() {
return [CartStore];
}
static getPropsFromStores() {
return CartStore.getState();
}
componentDidMount() { // tried componentWillMount also
CartActions.updateCart();
}
render() {
console.log(this.props.cart); // empty object
return (
<div className="cart">
{this.props.cart.map((item, i) => <div key={i}>{item.get('name')}</div>)}
</div>
);
}
}
export default connectToStores(Cart);Actions
class CartActions {
updateCart() {
this.dispatch();
}
}
export default alt.createActions(CartActions);商店
class CartStore {
constructor() {
this.bindActions(CartActions);
this.cart = Immutable.fromJS([]);
}
updateCart() {
this.cart = Immutable.fromJS(JSON.parse(localStore.getItem('cart')));
console.debug('cart', this.cart); // returns the correct object
}
}
export default alt.createStore(CartStore, 'CartStore');存储库接收操作事件并从localStorage检索正确的对象。但是,组件的道具不会像通常那样进行更新。
任何帮助都很感激!谢谢您:)
版本
发布于 2015-12-30 19:53:46
您需要在视图中的某个位置侦听存储,通常是componentDidMount,而且如果您正在从存储中表示某个内容,并且它会发生变化,那么它要么来自更高层次的组件,要么就变成了一个状态。在这种情况下,状态变量更适合。
所以,像这样的东西会有用
componentDidMount () {
CartStore.listen(this.onChange)
CartActions.updateCart()
}
onChange () {
this.setState({
xxx: xxxx
}) // or change props like yours if you insist
}
render() {
return (
<div className="cart">
{this.state.cart.map((item, i) => <div key={i}>{item.get('name')}</div>)}
</div>
);
}https://stackoverflow.com/questions/34526531
复制相似问题