我正在尝试使用从商店收到的新 Prop 重新渲染我的 React 组件,但 Prop 似乎没有更新。这种方法通常对我有用,只是在这种情况下不起作用。
组件
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);
操作
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 检索正确的对象。但是,组件的 props 不会像平常那样更新。
任何帮助表示赞赏!谢谢:)
版本
- react 0.14.3
- alt.js 0.17.9
最佳答案
您需要在 View 中的某个位置监听您的存储,通常是 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>
);
}
关于javascript - Flux/Alt 未从商店更新 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34526531/