我正在尝试使用上下文 api,但我的消费者返回值在控制台中未定义



这是我上下文的代码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;

,这是我打算使用它的地方,但它在控制台中返回未定义。我正在寻找一些帮助。

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;

我想知道我在上下文代码中是否做错了。

您在这里遇到的问题是您试图过早地破坏环境。我个人会将其分为3个文件。当您使用git文件历史记录时,它也会有所帮助!

  • user.context.js(这使导入更易于跟踪
  • 提供商 - 通常这将是最高节点(确实需要它!(
  • 消费者 - 消耗价值的组件

User.context.js

import { createContext } from "react";
export const UserContext = createContext();

提供商-<UserState />

import React, { Component } from "react";
import { UserContext } from '../../User.context.js' // some folder for context's
class UserState extends Component {
  state = {
    user: "JOHN"
  };
  render() {
    return (
      <UserContext.Provider value={this.state}>
        {this.props.children}
      </UserContext.Provider>
    );
  }
}
export default UserState;

消费者-<SignUpForm />

import React, { useContext } from "react";
import styled from "@emotion/styled";
import { UserContext } from '../../User.context.js' // some folder for context's
const StyledSignUp = styled.div`
  width: 50%;
  margin: 20px auto;
`;
// OLD WAY
const SignUpForm = ({ props, ...remainProps }) => {
  return (
    <UserContext.Consumer>
      {context => {
        console.log("CONTEXT API", context);
        return (
          <StyledSignUp {...remainProps}>
            <div className="content">content here</div>;
          </StyledSignUp>
        );
      }}
    </UserContext.Consumer>
  );
};
// React Hook way :)
const SignUpForm = ({ props, ...remainProps }) => {
  const context = useContext(UserContext);
  return (
    <StyledSignUp {...remainProps}>
      <div className="content">content here</div>;
      {/* Debug - Seeing is believing */}
      <pre>{JSON.stringify(context, null, 2)}</pre>
    </StyledSignUp>
  );
};
export default SignUpForm;

让我知道您如何上台!

相关内容

  • 没有找到相关文章

最新更新