在上下文使用者上使用useContext()时,反应上下文“属性'状态'不存在”

时间:2020-04-05 16:54:25

标签: javascript reactjs react-native react-hooks react-context

我正在尝试在我的React项目中实现Context。每次尝试实现此Context时,都会收到相同的错误:

Property 'state' does not exist on type '{ count: number; currentColor: string; }'.

  > 40 |   let { state, dispatch } = React.useContext(ContextOne);
       |         ^

上下文提供者代码:

import * as React from "react";

let ContextOne = React.createContext(initialState);

let initialState = {
  count: 10,
  currentColor: "#bada55"
};

let reducer = (state, action) => {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    case "set-color":
      return { ...state, currentColor: action.payload };
  }
};

function ContextOneProvider(props) {
  let [state, dispatch] = React.useReducer(reducer, initialState);
  let value = { state, dispatch };


  return (
    <ContextOne.Provider value={value}>{props.children}</ContextOne.Provider>
  );
}

let ContextOneConsumer = ContextOne.Consumer;

export { ContextOne, ContextOneProvider, ContextOneConsumer };

我尝试了许多在线示例上下文提供程序,但是每次调用useContext()时,都会出现相同的错误。要使上下文正常工作需要进行哪些修改?

------------------------------------------编辑---- --------------------------------------

感谢大豆,这是有效的上下文提供程序代码:

import * as React from "react";

type State = {
  count: number
  currentColor: string
}

const initialState: State = {
  count: 10,
  currentColor: "#bada55",
};

type Context = {
  state: State
  dispatch: React.Dispatch<Action>
}

type Action = {
  type: string,
  payload: string
}
const ContextOne = React.createContext<Context>({
  state: initialState,
  dispatch: () => {},
});

// You need to define the type Action
const reducer: React.Reducer<State, Action> = (state, action) => {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    case "set-color":
      return { ...state, currentColor: action.payload };
  }
};

function ContextOneProvider(props) {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  const value: Context = { state, dispatch };

  return (
    <ContextOne.Provider value={value}>{props.children} </ContextOne.Provider>
  );
}

let ContextOneConsumer = ContextOne.Consumer;

export { ContextOne, ContextOneProvider, ContextOneConsumer };

2 个答案:

答案 0 :(得分:1)

.panel-container { background-color: #000000; } .dashboard-container { background-color: #000000; } .navbar { background-color: #000000; } 参数类型应与您的createContext值类型匹配。您还需要改进类型,以更多地指导ContextOne.Provider编译器:

TypeScript

答案 1 :(得分:0)

您的问题是,您正在向上下文提供程序提供初始状态,该状态提供程序具有属性countcurrentColor,而您在ContextOneProvider中提供的值(新状态)具有属性statedispatch

我想您会希望将initialState交换为以下内容:

{
  state: null,
  dispatch: null,
}

如果您使用的是打字稿,则可能需要提供一个包含那些作为可选参数的接口。