如何解决使用从父组件中进行的异步api调用接收到的道具来更新react子组件的状态
我要做的是使用prop设置状态,但问题是我的prop来自父组件中的api调用(我正在使用react router dom)。因此,首先我尝试使用componentDidMount,该组件在您从欢迎页面(孩子)转到Home(孩子)时有效,但是当您直接进入主页时,组件确实在进行api调用之前装入了填充状态(基本上是未定义的)。>
接下来我尝试使用componentDidUpdate,当您直接转到Home(child)时它可以工作,但是当您从欢迎页面(child)到Home(child)时,componentDidUpdate甚至不会触发。(因此再次未定义)(componentdidupdate确实可以nt在组件初始化时运行,即首次创建组件) 另外,如果您导航到另一条路线并返回它在componentDidUpdate的情况下不起作用我认为组件生命周期从一开始就可以有人确认吗?
现在,我在代码中同时使用componentDidUpdate和componentDidMount,并且运行良好。我只想知道这是最好的方法,还是有另外一种方法来使用来自api调用的道具填充状态
家庭组件
constructor(props: HomeProps) {
super(props);
this.state = {
myUser: {},}
}
componentDidUpdate = (prevProps: HomeProps) => {
if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
this.setState({ myUser: this.props.userProfile });
}
}
componentDidMount = () => {
this.setState({ myUser: this.props.userProfile })
}
主要成分(母体) 欢迎:path =“ /” 主页:path =“ / Home”
<HashRouter>
<Switch>
<Route exact path="/" render={(props) => (<Welcome {...props} />)} />
<Route exact path="/Home" render={(props) => (<Home authContext={this.props.authContext} {...props} userProfile={this.state.currentUser} />)} />
</Switch>
</HashRouter>
只是想知道正确的方法,如果您能解释为什么更好,我也将不胜感激。
解决方法
我将以这种方式来构造它,而不是像父级-子级那样使用不同的路由,我将它们视为并行或同级。在那种情况下,我将使用Redux或您首选的状态管理。随着应用的增长和添加的更多路线,您必须将用户道具从“父路线”传递到所有将来的路线,这将成为维护问题。
使用像Redux这样的状态管理工具,所有组件都可以访问状态,无论路线走了多深或添加了多少同级路线,都无需将道具传递给每个组件。
,首先,您应该使用async / await api调用,如果您在api本身中使用async / await可以解决此问题,则可以像下面那样使用。
constructor(props: HomeProps) {
super(props);
this.state = {
myUser: {},}
}
componentDidUpdate = async(prevProps: HomeProps) => {
if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
await this.setState({ myUser: this.props.userProfile });
}
}
componentDidMount = async () => {
await this.setState({ myUser: this.props.userProfile })
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。