如何防止反模式:在以下情况下,无条件复制道具到状态

时间:2018-10-29 09:30:46

标签: reactjs

我有一个产品页面,该页面根据服务响应生成列表。 回复具有此表格

Service

我想在下一页(例如比较页)上比较产品。相比之下,页面用户可以从下拉列表中添加(最多4个)/更改所选产品。因此,从“产品页面”中,我正在发送如下数据

    [
    {name: P1,
    color:c1},
    {name: P2,
    color:c2},
    {name: P3,
    color:c3},
    {name: P4,
    color:c4}
    ]

还有其他设置状态的方法吗?因为这是反模式。

this.props.history.push('/compareproduct', {
    products: this.state.products,
    productsToCompare, // In form of [{name: P1, color:c1}, {name: P4, color:c4}]
  });

在路线上

constructor(props) {
    this.state = {productsToCompare: this.props.localtion.state.productsToCompare}
}

1 个答案:

答案 0 :(得分:0)

根据您在qn中的评论(其中比较产品不是产品组件的子项),我认为实现此目的最直接的方法是通过Context API。

1-创建一个Context.jsx组件

// export default ContextProvider;
import React, { Component } from 'react';

export const AppContext = React.createContext();

class ContextProvider extends Component {
    state = {
        productsToCompare: [],
    };

    updateProductsToCompare = newProducts => {
        // Logic to update the state here from your Products Page
        this.setState({ productsToCompare: newProducts });
    };
    render() {
        const { productsToCompare } = this.state;
        return (
            <AppContext.Provider value={{ productsToCompare, updateProductsToCompare: this.updateProductsToCompare }}>
                {this.props.children}
            </AppContext.Provider>
        );
    }
}

export default ContextProvider;

2-在ContextProvider中包装您或根组件(由上述组件导入) 3-在“ /产品”页面中:

<AppContext.Consumer>
    {({ updateProductsToCompare }) => (
        <div>Component here. Use function to update state in context</div>
    )}
</AppContext.Consumer>

4-在“ /比较”页面中:与上述相同,但是比较产品

<AppContext.Consumer>
    {({ productsToCompare }) => (
        <div>Component here. Use products to compare stored in context</div>
    )}
</AppContext.Consumer>
相关问题