猿问

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

你有想念' td' $('#' + rowId)将是$('#' + rowId+ ' td')


 $('#' + rowId+ ' td').each(function() {

     $('td').css('border-top', '1px solid #7f7f7f');

 });我正在尝试在我的 React 项目中实现上下文。每次我尝试实现这个上下文时,我都会得到同样的错误:


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() 时,都会出现相同的错误。需要修改哪些内容才能使 Context 正常工作?


慕码人8056858
浏览 116回答 2
2回答

慕娘9325324

createContext参数类型应与您的值ContextOne.Provider类型匹配。您还需要改进您的类型以指导更多的TypeScript编译器:import * as React from "react";type State = {&nbsp; count: number&nbsp; currentColor: string}const initialState: State = {&nbsp; count: 10,&nbsp; currentColor: "#bada55",};type Context = {&nbsp; state: State&nbsp; dispatch: React.Dispatch<State>}const ContextOne = React.createContext<Context>({&nbsp; state: initialState,&nbsp; dispatch: () => {},});// You need to define the type Actionconst reducer: React.Reducer<State, Action> = (state, action) => {&nbsp; switch (action.type) {&nbsp; &nbsp; case "reset":&nbsp; &nbsp; &nbsp; return initialState;&nbsp; &nbsp; case "increment":&nbsp; &nbsp; &nbsp; return { ...state, count: state.count + 1 };&nbsp; &nbsp; case "decrement":&nbsp; &nbsp; &nbsp; return { ...state, count: state.count - 1 };&nbsp; &nbsp; case "set-color":&nbsp; &nbsp; &nbsp; return { ...state, currentColor: action.payload };&nbsp; }};function ContextOneProvider(props) {&nbsp; const [state, dispatch] = React.useReducer(reducer, initialState);&nbsp; const value: Context = { state, dispatch };&nbsp; return (&nbsp; &nbsp; <ContextOne.Provider value={value}>{props.children} </ContextOne.Provider>&nbsp; );}let ContextOneConsumer = ContextOne.Consumer;export { ContextOne, ContextOneProvider, ContextOneConsumer };

慕标5832272

您的问题是您正在向具有属性的上下文提供者提供初始状态countand currentColor,而您提供的值(新状态)ContextOneProvider具有属性stateand dispatch。我想您会希望将 initialState 交换为以下内容:{&nbsp; state: null,&nbsp; dispatch: null,}如果您使用的是打字稿,您可能希望提供一个将这些作为可选参数的接口。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答