试图转换成打字稿..无法弄清楚如何制作动作类型和有效负载..我正在使用 useContext 并使用 Reducer 我基本上希望我的动作从提供的 ./types 的键中获取类型,然后找出方法提供pyaoad 这是我的状态
import React, { useReducer } from "react"
import AlertContext from "./AlertContext"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import AlertReducer from "./AlertReducer"
import { IAlertState } from "../IAlertState"
export interface typealert{
variant : string,
text: string,
}
const AlertState = (props : any) =>{
const initialState :IAlertState = {
alert:{
variant :'',
text :''
}
}
const [state,dispatch] = useReducer(AlertReducer,initialState)
const showAlert =(variant : string,text : string) =>{
dispatch({type:SHOW_ALERT,payload:{variant,text}})
setTimeout(()=>{
setAlert({variant:'',text:''})
},2000)
}
const setAlert =(alert : typealert) => dispatch({type :REMOVE_ALERT,payload:null})
return(
<AlertContext.Provider value={{
alert:state.alert,
showAlert
}}>
{props.children}
</AlertContext.Provider>
)
}
导出默认 AlertState
这是我的减速机
import React from "react"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import { IAlertState } from "../IAlertState"
export interface IActionTypes{
type : any,
payload : any
}
export default (state : IAlertState ,action : IActionTypes) =>{
switch(action.type)
{
case SHOW_ALERT:
return{
...state,
alert:{
variant : action.payload["variant"],
text:action.payload["text"]
}
}
case REMOVE_ALERT:
return{
...state,
alert:{
variant: '',
text:''
}
}
default : return state
}
}
在此,我提供的操作类型是任何类型,但我希望它是来自 ./types 文件的类型
export const SEARCH_USERS = 'SEARCH_USERS'
export const GET_USER ='GET_USER'
export const GET_REPOS = 'GET_REPOS'
export const CLEAR_USERS ='CLEAR_USERS'
export const SHOW_ALERT ='SHOW_ALERT'
export const SET_LOADING ='SET_LOADING'
export const USER_LOADING ='USER_LOADING'
export const REMOVE_ALERT ='REMOVE_ALERT'