reactjs - 获取后如何从道具设置初始状态?
问题描述
我想使用 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 之前调用了构造函数。这意味着组件的初始状态设置不正确。
在所有数据准备好之前,我需要一些方法来防止组件被渲染
解决方案
如果你想使用给组件的 props 作为初始状态,并且这些 props 是异步获取的父组件中的状态,你需要延迟子组件的渲染。
例如,您可以添加一个额外的状态,称为isLoading
您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} />;
}
}
推荐阅读
- javascript - 如果我为 Date.prototype.getTime() 提供参数怎么办?
- javascript - Javascript 仅返回字符串 url 的子域部分
- azure-data-factory - Azure 数据工厂:如果自托管 IR 关闭会发生什么
- javascript - 如何为带有 sinon 的函数传递假参数并期望指定的返回值
- html - 反应打开子路由中的href而不是新链接
- javascript - 如何关闭/关闭赛普拉斯中的基本身份验证提示窗口?
- javascript - 反应重新填充现有的检查输入字段
- django - How can I extract URL of the video uploaded using Django Embed video
- java - Minecraft 的 3D 块模型作为项目工作,但在放置时变为空块(Minecraft Modding 1.16.5)
- nginx - nginx 上的反向代理 - 不向请求添加端口