这是我的上下文 api 的代码
import React, { Component } from "react";
const { Provider, Consumer } = React.createContext();
const MyContextProvider = Provider;
const MyContextConsumer = Consumer;
export { MyContextConsumer, MyContextProvider };
class UserState extends Component {
state = {
user: "JOHN"
};
render() {
return (
<MyContextProvider value={this.state}>
{this.props.children}
</MyContextProvider>
);
}
}
export default UserState;
这就是我打算使用它的地方,但它在控制台中返回 undefined 。我正在寻求帮助。
import React from "react";
import styled from "@emotion/styled";
import { Formik, Form, Field, ErrorMessage } from "formik";
import { MyContextConsumer } from "../../context/UserStateContext";
const StyledSignUp = styled.div`
width: 50%;
margin: 20px auto;
`;
const SignUpForm = ({ props, ...remainProps }) => {
return (
<StyledSignUp {...remainProps}>
<MyContextConsumer>
{context => {
console.log(context, "CONTEXT API");
return <div className='content'>content here</div>;
}}
</MyContextConsumer>
</StyledSignUp>
);
};
export default SignUpForm;
我想知道我是否在上下文代码中做错了什么。