UseReducer更改状态

时间:2020-05-04 05:13:59

标签: reactjs react-hooks

我只是制作了一个简单的应用,其中我从api获取数据,然后显示其标题。在初始渲染时,它可以正常工作,但是每当我尝试通过提供input(number)来更改值时,它都无法正常工作。有人可以帮我指出我的代码有什么问题吗? TIA 这是我的代码的屏幕截图。 https://i.imgur.com/fogYFvT.png
https://i.imgur.com/Q811Bd3.png

import React, {useReducer, useEffect} from "react"
import axios from "axios"

const initialState = {
    isLoading : true,
    isError : '',
    id: 1,
    fetchedData : {}    
}

const actionHandler = (state,action) => {
    switch(action.type)
    {       
        case 'success' : 
            return {
                isLoading : false,
                isError : '',
                fetchedData: action.fetchedData
            }
        case 'error': 
            return {
                isLoading : false,
                isError : 'Something went wrong!',
                fetchedData: {}
            }
        case 'change' : 
            return {...initialState, id : action.value}
    }
}

function HooksUseReducerDataFetchingApp()
{
    const [data,action] = useReducer(actionHandler,initialState);
    useEffect(() => {
        axios.get(`https://jsonplaceholder.typicode.com/posts/${data.id}`)
            .then(response => {
                action({type:'success', fetchedData: response.data, error : 1000})                              
            })
            .catch(error => {               
                action({type:'error'})
            })
    }, [data])
    return(
        <>
            {data.isLoading ? 'Loading...' : console.log(data) }
            { data.isError ? data.isError : null }<br />
            <input 
                type="number"
                placeholder = "Enter a number"
                value = {data.id}
                onChange = { (e) => action({type: 'change', value: e.target.value }) }
            />
        </>
    )
}

export default HooksUseReducerDataFetchingApp

1 个答案:

答案 0 :(得分:1)

您正在axios呼叫中传递initialState.id。相反,您需要将data.id作为useEffect依赖项传递,并在axios调用中传递它。

您需要在actionHandler中使用state值以获得正确的值:

const actionHandler = (state,action) => {
    switch(action.type)
    {       
        case 'success' : 
            return {
                ...state
                isLoading : false,
                isError : '',
                fetchedData: action.fetchedData
            }
        case 'error': 
            return {
                ...state,
                isLoading : false,
                isError : 'Something went wrong!',
                fetchedData: {}
            }
        case 'change' : 
            return {...state, id : action.value}
    }
}