【发布时间】:2023-03-29 15:13:01
【问题描述】:
我从 typescript 收到以下 linting 错误,但我不知道确切原因,因为 IBlockchainContextValue 已经具有其 IBlockchainContextState 类型的 state 属性,同时已经具有所有这些加载、帐户...属性.. .也许最好看一下代码和附图来理解Typescript问题。
// Blockchain context
import React from 'react';
interface IBlockchainContextState {
loading: boolean;
account: string;
tokemonToken: any; // TODO
web3: any; // TODO
errorMessage: string;
}
interface IBlockchainContextValue {
state: IBlockchainContextState;
dispatch: React.Dispatch<any>;
}
const initialState: IBlockchainContextState = {
loading: false,
account: '',
tokemonToken: null,
web3: null,
errorMessage: '',
};
const BlockchainContext =
React.createContext<IBlockchainContextState>(initialState);
const BlockchainContextProvider: React.FC<IBlockchainContextValue> = ({
children,
}) => {
const [loading, setLoading] = React.useState(false);
const [account, setAccount] = React.useState('');
const [tokemonToken, setTokemonToken] = React.useState(null);
const [web3, setWeb3] = React.useState(null);
const [errorMessage, setErrorMessage] = React.useState('');
// Context Update Setters
const blockchainReducer = (
state: IBlockchainContextState,
action: any
): IBlockchainContextState => {
switch (action.type) {
case 'SET_LOADING':
return { ...state, loading: action.payload };
case 'SET_ACCOUNT':
return { ...state, account: action.payload };
case 'SET_TOKEN':
return { ...state, tokemonToken: action.payload };
case 'SET_WEB3':
return { ...state, web3: action.payload };
case 'SET_ERROR_MESSAGE':
return { ...state, errorMessage: action.payload };
default:
return state;
}
};
const [state, dispatch] = React.useReducer(blockchainReducer, initialState);
const blockchainContextValue = React.useMemo(
() => ({
state,
dispatch,
}),
[state, dispatch]
);
return (
<BlockchainContext.Provider value={blockchainContextValue}>
{children}
</BlockchainContext.Provider>
);
};
export { BlockchainContext, BlockchainContextProvider };
【问题讨论】:
标签: reactjs typescript types react-hooks