-1

typescriptに変換しようとしています..アクションタイプとペイロードを作成する方法を理解できません..私はuseContextを使用してReducerを使用しています.ピラロードを提供するには、これが私の状態です

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