reactjs - react : Getting props to load on initial render

标签 reactjs

this.props.allStagesData 来自父组件中的 AJAX 请求。如果我注释掉 console.log('stageID', currentStage._id);,则在我最终获取数据之前,该组件当前会加载 3 次。当该日志取消注释时,它会抛出 Uncaught TypeError: Cannot read property '_id' of undefined,因为我还没有数据。

如何在初始渲染时加载此数据?

export default class NavMain extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      stagesData: []
    }
  }
  componentWillMount() {
    var stagesData = this.props.allStagesData;

    this.setState({
      stagesData: stagesData
    })
  }
  render() {
    var  stagesData = this.state.stagesData,
         currentStage = _.find(stagesData, {'_status': "open"});

      console.log('this.props.allStagesData', this.props.allStagesData);
      console.log('this.state.stagesData', stagesData);
      console.log('currentStage', currentStage);
      console.log('stageID', currentStage._id);

    return (
      ...
    )
  }
}

console

(忽略图像中的两个错误,它们是无关的。)

最佳答案

在数据到达之前,您可以简单地返回其他内容,或者null。尝试将 if(this.state.stagesData.length === 0) return null 添加到渲染函数的第一行。这样,在数据实际存在之前,它不会显示。

编辑:为了回答您的问题,数据不能在第一次渲染时出现。更好的方法是返回包含除数据之外的所有内容的 HTML,或者如上所述简单地返回 null,直到请求完成。如果需要,您还可以渲染加载指示器!

关于reactjs - react : Getting props to load on initial render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497329/

相关文章:

javascript - 将 createStore 替换为 configureStore

javascript - 如何在 jest/enzyme 测试中测试 axios get 请求函数?

reactjs - React 中的表单性能是否不佳?

javascript - 如果状态是某种东西,则执行 .filter 和 .map,否则仅执行 .map

javascript - ReactJS 应用程序中的 Chart.js : no terminal error, 但没有渲染

javascript - React 导入中的点表示法

javascript - ReactJS:React.render 不是函数,React.createElement 也不是函数

reactjs - React Auth 状态和 Routes 。无法在 React-Router 内的 'replaceState' 上执行 'History'

javascript - 第一次使用 AbortController 时清理功能失败

javascript - 对象分配和传播运算符会改变 React 状态?