下面的代碼向我拋出錯誤:
frontend_1 | TypeScript error in /frontend/src/State/Store.tsx(23,27):
frontend_1 | Property 'test' is missing in type 'any[]' but required in type '{ test: string; }'. TS2741
frontend_1 |
frontend_1 | 21 |
frontend_1 | 22 | return (
frontend_1 | > 23 | <Context.Provider value={[state, dispatch]}>
frontend_1 | | ^
frontend_1 | 24 | {children}
frontend_1 | 25 | </Context.Provider>
frontend_1 | 26 | )
import { createContext, useReducer } from "react";
const initialState = {
test: "text-string"
}
const reducer = (state: any, action: any): any => {
switch (action.type) {
case 'SET_PUBLIC_KEY':
return {
...state,
}
default:
return state;
}
};
function Store({ children }: any) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
)
};
export const Context = createContext(initialState);
export default Store;
我試圖修復它幾個小時,但無論我嘗試過什么,它仍然會引發同樣的錯誤。如果有人能幫助我,我真的很感激。這個例子像一個魅力一樣在普通的 javascript 中作業,所以這個問題只出現在打字稿中。
提前致謝!
uj5u.com熱心網友回復:
value傳遞給提供者的(具有狀態和調度的陣列)的型別和傳遞給的initialState(僅狀態)的型別createContext是不同的。只要確保這兩個值是相同的型別。
您可以為 reducer 的 state、action 定義介面并在任何地方使用它們。
interface State {
test: string;
}
interface Action {
type: string;
payload?: any; // update this as you like
}
const initialState = {
test: "text-string"
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case "SET_PUBLIC_KEY":
return {
...state,
test: "modifed"
};
default:
return state;
}
};
// passing an array that matches the type of context's value
export const Context = createContext<[State, Dispatch<Action>]>([
initialState,
() => initialState
]);
function Store({ children }: any) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
);
}
const Child = () => {
const [state, dispatch] = useContext(Context);
return (
<div onClick={() => dispatch({ type: "SET_PUBLIC_KEY" })}>{state.test}</div>
);
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Store>
<Child />
</Store>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397226.html
