javascript - Flux/Alt 未从商店更新 Prop

标签 javascript reactjs flux alt immutable.js

我正在尝试使用从商店收到的新 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/

相关文章:

javascript - 在 Javascript 中跟踪 Hashmap 的两次访问有什么不同吗

javascript - 页面加载时调用函数

reactjs - React-Router 和 Flux - 转换时清除状态

reactjs - UI 事件的 Flux 操作

javascript - PHP 中包含模板时删除旧内容

javascript - 如何从 JSON 数据制作 FlightPlanCoords?

javascript - Axios - 删除带有请求正文和 header 的请求?

javascript - React Deploying to AWS S3 production using npm - index.html 文件作为最后

javascript - 在 react 中过滤 geojson 的最佳方法?

javascript - 没有 React 的 Flux