【问题标题】:react-redux connect() function mapStateToProps is updating but component not re-renderingreact-redux connect() 函数 mapStateToProps 正在更新,但组件未重新渲染
【发布时间】:2020-06-01 07:26:25
【问题描述】:

我正在使用 React、Redux 和 React-Redux Provider 函数

const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return store.textTwo;
};

如果我将上面的mapStateToProps 函数使用到react-reduxconnect 方法并更新状态,它将console.log 更改mapStateToProps 函数而不是重新渲染组件,甚至不会出现componentWillReceiveProps 钩子。

但是当我添加spread operator 即改变mapStateToProps 返回数据时,它将重新渲染完整的组件。

const mapStateToProps = (store: any) => {
    console.log("mapStateToProps", store.textTwo);
    return { ...store.textTwo }; <-- this will re render complete component
};

如何在不重新渲染完整组件的情况下将状态传递给组件的 props。

--- 更新---

样本状态数据

store = {
    textTwo: {
        headerText: 'Sample',
        list: [
            {
                id: 1,
                name: 'test 1'
            }
        ]
    },
    text: {}
}

headerText 是显示标题标题的子组件。 list 是我正在迭代并列出名称的数据数组。

尝试了以下解决方案(由@Siva Kondapi Venkata 提供)并且它正在工作,但是如果我在列表中添加一个新项目,标题组件也会重新渲染。

const mapStateToProps = (store: any) => ({
  textTwo: store.textTwo
});

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    你需要这样做。回复你感兴趣的props

    const mapStateToProps = (store: any) => ({
      textTwo: store.textTwo
    });
    
    const mapDispatchToProps = {
    
    };
    
    export default connect(mapStateToProps, mapDispatchToProps)(Component);
    

    【讨论】:

    • 谢谢,它正在工作,但它仍在重新渲染完整的组件,更新问题添加示例数据和场景,请查看
    • @skdroid,如果您的子组件中没有使用列表,您可以将其更改为headerText: store.textTwo.headerText。如果您使用来自 2 个属性的派生值,则可以使用选择器(react-select)。你也可以发布组件代码吗?更好地理解。
    • 其实我同时使用了headerText和list,headerText传给Header子组件,list传给list组件,这两个组件基本上都是用来显示数据的功能组件。
    猜你喜欢
    • 2018-12-12
    • 2018-10-15
    • 2017-07-22
    • 1970-01-01
    • 2017-06-17
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多