如何使用 connectToStores 在可变 react.js 组件中更新状态与道具

How to update state vs props in a fluxible react.js component using connectToStores

所以我不确定我是否完全理解 connectToStores 在我的搜索结果组件中的作用。我希望在我的商店发出更改时更新组件的状态,但它似乎只是在更新组件的属性并更新包装 SearchResultsConnector 对象的状态。

我的问题是:

  1. 在这种情况下我不应该使用状态吗?如果是这样,为什么 connectToStores 有一个 returns 状态的回调?

  2. state 何时从商店中的 emitChanges 触发器更新?我必须复制我在构造函数中所做的吗?

  3. 我什么时候应该使用 state 与 props,并且应该存储更新状态?是否有特定的通量规则支持以单向方式改变状态?

  4. 为什么当我在开发服务器中热加载更改时,状态会更新为结果。我不明白这是否是正确的行为。

  5. 我是否应该在此处某处捕获更新事件并以某种方式使用传入的更改属性更新状态?

SearchResults.js

import React from 'react';
import SearchStore from '../stores/SearchStore';
import Product from './Product';
import connectToStores from 'fluxible-addons-react/connectToStores'


class SearchResults extends React.Component {

    static contextTypes = {
        executeAction: React.PropTypes.func.isRequired,
        getStore: React.PropTypes.func.isRequired
    };
    static propTypes = {
        results: React.PropTypes.array
    };
    static defaultProps = {
        results:[]
    };
    constructor(props) {
        super(props);
        this.state = {results: props.results};
    }
    render() {

        let main;

        // I first used this.state.results, but this.state is null unless I hot load from the dev server on changes
        if (this.props && this.props.results && this.props.results.length) {

            let products = this.props.results.map(function (product) {
                return (
                    <Product
                        key={product.id}
                        imageUrl={product.image_url_large}
                        description={product.description}
                        name={product.name}
                        maxPrice={product.price_max}
                        minPrice={product.price_min}
                    />
                );
            }, this);

            main = (
                <section id="results">
                    <ul id="todo-list">
                        {products}
                    </ul>
                </section>
            );
        }

        return (
            <div>
                <header id="header">
                    <h1>Search Results</h1>
                </header>
                {main}
            </div>
        );
    }

}

SearchResults = connectToStores(SearchResults, [SearchStore], (context, props) => ({
    results: context.getStore('SearchStore').getResults()
}))


export default SearchResults;

connectToStores 是一个 returns 'higher order component' 基于您提供的组件(您作为第一个参数输入的 SearchResults)的函数。

如果您查看实现 here(第 44 行,storeConnector 的渲染方法),它基本上将您提供的状态传输到返回对象的道具。所以是的,您应该从组件中的道具而不是状态中获取值以进行渲染。

如果你有兴趣知道为什么我们要使用高阶组件,你可以看看this article