首页 > 解决方案 > ReactJS 在收到新的 props 后更新视图

问题描述

在几个月没有使用 ReactJS 后再次安装后,我注意到最新版本 (16) 现在正在使用 getDerivedStateFromProps 并且没有更多将接收道具功能和东西。

目前,我的环境运行包含 react-redux。我的新数据进入容器脚本的 mapStateToProps 函数,但我想相应地更新视图。基本上是一个加载屏幕,在通过 API 调用获取数据后,使用 API 的响应数据更新视图。但是,到目前为止,我似乎无法找到在任何地方更新我的视图的解决方案。

我注意到 getDerivedStateFromProps 只被触发一次。

我是否缺少某些功能或任何东西?简短的例子:

import React from 'react';
import { connect } from "react-redux";

import Files from '../components/files';

class ProjectContainer extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.getFilesByShare('sharename');
  }

  componentDidUpdate (prevProps) {
      console.warn('does not get here?');
  }

  render() {
    const { loading, files } = this.props;

    let content = (
      <div className="loading">Loading... Requesting file urls</div>
    );

    if (!loading && files && files.length) {
      content = (
        <div>
          File urls requested!
          <Files files={files} />
        </div>
      );
    }
    return (
      {content}
    );
  }
}

const mapStateToProps = state => {
  console.warn(state, 'this shows the new data');
  return {
    files: state.files,
    loading: state.files_loading,
  };
};

export default connect( mapStateToProps, { 
  getFilesByShare,
}) (ProjectContainer);

标签: reactjs

解决方案


推荐阅读