如何在获取后从道具设置初始状态?

问题描述 投票:1回答:1

我想使用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之前,组件会调用构造函数。这意味着组件的初始状态未正确设置。

我需要一些方法来防止组件被渲染,直到所有数据都准备好

reactjs jsx
1个回答
1
投票

如果要将赋予组件的props用作初始状态,并且这些props是异步提取的父组件中的状态,则需要延迟子组件的呈现。

你可以,例如添加一个名为isLoading的状态,在fetch完成时设置为false并使用它来有条件地渲染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} />;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.