-1

试图转换成打字稿..无法弄清楚如何制作动作类型和有效负载..我正在使用 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'
4

1 回答 1

0
type ActionTypes =
  | {
      type: SEARCH_USERS;
      payload: IAlertState["alert"];
    }
  | {
      type: REMOVE_ALERT;
      payload: void;
    }

  | ....

使用联合类型来建模你的有效负载和类型,因为类型是区分联合类型的自然标签,你的代码将得到良好的类型和适当的缩小

于 2020-06-01T09:22:24.603 回答