简体   繁体   English

即使没有更改,React 也会重新渲染

[英]React re-renders even with no change

We have set up a project with redux.我们已经建立了一个带有 redux 的项目。 In this project, we get an info objecat from an api and insert it into the store.在这个项目中,我们从一个 api 中获取一个 info objecat 并将其插入到 store 中。 Now we noticed that the function components re-render even if the api return the same state as in the previous request.现在我们注意到,即使 api 返回与前一个请求相同的状态,函数组件也会重新渲染。

We think it's because we are overwriting the store but we are not sure.我们认为这是因为我们正在覆盖商店,但我们不确定。

ChatContainer.js聊天容器.js

const mapStateToProps = function (state) {
  return {
    content: state.info.content,
    loading: state.info.loading,
  }
}

const ChatContainer = connect(
  mapStateToProps,
)(Chat)
export default ChatContainer

Chat.js聊天.js

function Chat(props) {

    const { content, loading } = props;
    return (
        <Info content={content} loading={loading} />
    ) 
}

action.js动作.js


export function setInfo(info) {
  return {
    type: SET_INFO, info: {
      content: info,
      loading: false
    }
  }
}

reducer.js减速器.js

function setInfo(state = { content: [], loading: true }, action) {
  switch (action.type) {
    case SET_INFO:
      return action.info
    default:
      return state
  }
}

const appReducer = combineReducers({
...
  info: setInfo,
...
})
export default appReducer

If state.info.content is an object, every time you change it with setInfo it will have a new reference.如果 state.info.content 是一个对象,则每次使用 setInfo 更改它时,它都会有一个新的引用。 React-redux does a shallow compare on the result of mapStateToProps, so if your content is a different reference every time your component will re-render. React-redux 对 mapStateToProps 的结果进行了浅层比较,因此如果您的内容每次重新渲染时都是不同的引用。 connect HOC has an options parameter that you can use to implement a custom compare. connect HOC 有一个 options 参数,您可以使用它来实现自定义比较。

My advice would be to add a check to your setInfo or to the code calling setInfo and not calling your API if data is already loaded/didn't change(don't know your business logic).我的建议是在您的 setInfo 或调用 setInfo 的代码中添加一个检查,如果数据已经加载/未更改(不知道您的业务逻辑),则不要调用您的 API。

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

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