对获取的数据做出反应

react context with fetched data

我正在使用 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。因为如果我用 "toto" 在 app.js 中初始化 username,它将显示 "toto"。

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

中执行 this.setState

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

这是一种遗留方法...但是,它尚未弃用!

您未在消费者(Header 组件)中声明 contextType

class Header extends Component {
  static contextType = UserContext;// you are missing this one
  constructor(props, context) {
    super(props, context);
    this.state = {
      username: context.username
    };
  }
  render() {
    console.log(this.state.username);
    return <React.Fragment>{this.state.username}</React.Fragment>;
  }
}