首页 > 解决方案 > 获取后如何从道具设置初始状态?

问题描述

我想使用 fetch() 获取数据并将其传递到我的组件层次结构中,并使用该数据设置我的一个组件的初始状态

我尝试使用道具设置初始状态并将它们传递下去。

componentDidMount = () => {
        getFileSystem().then(response => {
            if (response.success) {
                this.setState({
                    filesystem: response.filesystem,
                    projects: response.projects
                })
            }
        }).catch(err => {
            this.setState({
                filesystem: {
                    name: '/',
                    type: 'directory',
                    children: [
                        { name: 'error.txt', type: 'file', data: 'error' }
                    ]
                },
                projects: []
            })
        })

    }
class TerminalContainer extends Component { 

    constructor(props) {
            super(props)
            this.state = {
                filesystem: props.filesystem,
                terminal_data: [''],
                current_dir_name: '/',
                current_dir: props.filesystem,
                full_path: ""
            }
        }
...

但是组件在数据加载到组件的 props 之前调用了构造函数。这意味着组件的初始状态设置不正确。

在所有数据准备好之前,我需要一些方法来防止组件被渲染

标签: reactjsjsx

解决方案


如果你想使用给组件的 props 作为初始状态,并且这些 props 是异步获取的父组件中的状态,你需要延迟子组件的渲染。

例如,您可以添加一个额外的状态,称为isLoadingfalse在获取完成时设置的状态,并使用它来有条件地呈现TerminalContainer组件。

例子

class App extends React.Component {
  state = {
    isLoading: true,
    filesystem: null,
    projects: null
  };

  componentDidMount() {
    getFileSystem()
      .then(response => {
        if (response.success) {
          this.setState({
            isLoading: false,
            filesystem: response.filesystem,
            projects: response.projects
          });
        }
      })
      .catch(err => {
        this.setState({
          isLoading: false,
          filesystem: {
            name: "/",
            type: "directory",
            children: [{ name: "error.txt", type: "file", data: "error" }]
          },
          projects: []
        });
      });
  }

  render() {
    const { isLoading, filesystem } = this.state;

    if (isLoading) {
      return null;
    }
    return <TerminalContainer filesystem={filesystem} />;
  }
}

推荐阅读