简体   繁体   English

反应/Redux mapStateToProps by ownProps

[英]React/Redux mapStateToProps by ownProps

I'm trying to add a component in react which will get updates from websockets (already working) according its property:我正在尝试在 react 中添加一个组件,该组件将根据其属性从 websockets(已经工作)获取更新:

<div><Temperature room='livingroom'/></div>
<div><Temperature room='cellar'/></div>

The update should only be done for the component with the room property, which is mapped with mapStateToProps:应该只对具有 room 属性的组件进行更新,该属性使用 mapStateToProps 进行映射:

  function mapStateToProps(state, ownProps){
     if (ownProps.room == state.dataReducer.room_name){
        return { temp: state.dataReducer.temp,
                 room_name: state.dataReducer.room_name}
               }
  }

export default connect(mapStateToProps)(TOB);

The component definition:组件定义:

    const Temperature = ({room_name, temp}) => (
       <ul> {temp} </ul>
    );

Now every update I get (can happen async) one component is blank while the other is filled by the right temperature so it starts to flicker on frequent updates.现在,我获得的每次更新(可能异步发生)一个组件是空白的,而另一个组件被正确的温度填充,因此它在频繁更新时开始闪烁。

Do you have any idea how to do this updating by properties the right and working way?您知道如何以正确且有效的方式通过属性进行更新吗?

Your mapState function should always return the data this component needs, regardless of what action has been dispatched or how the store has been updated.您的mapState function 应始终返回此组件所需的数据,无论已调度什么操作或如何更新存储。 React-Redux will then check to see if the data for this component has actually changed since last time, and only re-render it if the data has changed.然后 React-Redux 将检查该组件的数据自上次以来是否实际发生了变化,只有在数据发生变化时才重新渲染。

Right now, your mapState function is only returning data some of the time.现在,您的mapState function有时只返回数据。 You should rewrite it so that every instance of Temperature is always extracting whatever data it needs from the store.您应该重写它,以便Temperature的每个实例总是从存储中提取它需要的任何数据。

(As a side note: don't name state slices as "state.somethingReducer" . Name them after the data that's contained inside .) (附带说明: 不要将 state 切片命名为"state.somethingReducer" 。以包含在其中的数据命名它们。)

You should use shouldComponentUpdate on your Temperature component to decide if you want it to render or not.您应该在温度组件上使用 shouldComponentUpdate 来决定是否要渲染它。 The component will render only if the return value evaluate to true仅当返回值评估为 true 时组件才会呈现

shouldComponentUpdate(nextProps) {
  return nextProps.room === nextProps.room_name;
}

function mapStateToProps(state){
  return 
    { temp: state.dataReducer.temp,
      room_name: state.dataReducer.room_name
  }
}

export default connect(mapStateToProps)(TOB);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM