gpt4 book ai didi

javascript - 对获取的数据使用react

转载 作者:行者123 更新时间:2023-11-30 06:10:39 26 4
gpt4 key购买 nike

我正在使用 React 和 NextJS。我想要的是将有关我的用户的数据发送到我的所有页面,为此我正在使用上下文。问题是,我从 api 获得了我的用户数据,但我的页面似乎没有获得更新的数据。这是我的 app.js :

...
import Header from '../component/header'
export default class MyApp extends App {
state = {
username: null
};
componentDidMount() {
fetch('API-URL', details_no_care)
.then(response => response.json())
.then(data => this.setState({username : data}));
}
render() {
const {Component, pageProps} = this.props;
return (
<React.Fragment>
<Head>
<title>My title</title>
</Head>
<UserContext.Provider value={{username : this.state.username}}>
<Header/>
<Component {...pageProps} />
</UserContext.Provider>
</React.Fragment>
);
}

}

这是我的用户上下文:

import React from "react";
export const UserContext = React.createContext(
);

还有我的 header.js :

class header extends React.Component {
constructor(props, context) {
super(props,context);
this.state = {
username: context.username
}
}
render () {
return (
<React.Fragment>
{this.state.username}
</React.Fragment>
)
}
}


但它从不显示任何内容。

我 100% 确定数据可以从应用程序传输到 header 。因为如果我在 app.js 中用“toto”初始化 username,它将显示“toto”。

此外,如果我在 componentDidUpdateconsole.log(this.context.username) 我确实有正确的数据。但是 React 不允许我在 componentDidUpdate

中执行 this.setState

最佳答案

所以我找到了解决方案。我没有使用状态。在我使用 this.state.user 的所有地方,我都将其替换为 this.context.user。看起来它正在工作。不要犹豫,告诉我这是一种不好的做法还是什么!

关于javascript - 对获取的数据使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com