【问题标题】:React-redux component not re-rendering on store props changeReact-redux 组件不会在商店道具更改时重新渲染
【发布时间】:2019-09-22 19:55:57
【问题描述】:

尽管 props 已更新,但我的 react 组件并未重新渲染,我不明白为什么。

这是我的组件

import { fetchLocations } from 'state/locations/actions';

class Event extends React.Component {

  componentDidMount() {
    this.props.fetchLocations();
  }

  render() {
    const { locations } = this.props;

    return <span>{locations.map((l) => {return <span>{l}</span>;})}</span>;
  }
}

const mapStateToProps = (state) => ({
  locations: state.locations
})

export default connect(                                                                                                                                               
  mapStateToProps,                                                                                                                                                    
  { fetchLocations },                                                                                                                                                 
)(Event); 

这是我的位置操作文件

export const fetchLocations = () = (dispatch) => {
  axios.get('/api/locations')
  .then(response => {
    const locations = response.data;

    dispatch({ type: FETCH_LOCATIONS_SUCCESS, payload: locations });
  });
}

还有我的实体减速器

function entities(state = { locations: {} }, action) {
  switch (action.type) {
    case FETCH_LOCATIONS_SUCCESS:
      return Object.assign({}, state, {
        locations: action.payload
      })
    default:
      return state
  }
}

在此之后,我的 Event 组件应该重新渲染。它没有。使用 react dev tools chrome 扩展,我看到这些位置确实在props 那里,但它们没有显示在 UI 上。

如果我通过转到其他页面来卸载组件并重新安装它,则位置会正确显示。

看起来一切正常,除了重新渲染没有触发。 componentDidUpdate 永远不会被解雇。

如果我在任意秒后手动将setTimeout 转换为forceUpdate,它们就会出现。

为什么我的组件没有重新渲染?

【问题讨论】:

  • 你有没有在componentDidUpdate 中尝试过console.log() 看看它是否在触发?另外,这看起来不像完整的代码,你能把完整的代码贴出来吗?
  • @RohitKashyap 是的,它没有触发。其他代码与问题imo没有真正的关系,您指的其他代码是什么?
  • 您已将位置分配为减速器内初始状态的对象,您正在尝试映射对象,将位置设置为空数组或''
  • 对不起,我遗漏了一些东西。我忘了在我的渲染函数中设置位置。 locations 在我的代码中也已正确设置。

标签: javascript reactjs redux react-redux


【解决方案1】:

请尝试将 key prop 添加到 render 方法的 span 元素。 locations.map((l,key)=&gt; &lt;span key={key} &gt;{l} &lt;/span&gt;

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 2017-07-22
    • 2021-12-04
    • 1970-01-01
    • 2021-09-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多