-1

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

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

4

1 回答 1

0

您在这里遇到的问题是您试图过早地解构上下文。就我个人而言,我会将其拆分为 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;

让我知道你是怎么办的!

于 2019-06-23T22:18:44.897 回答