我只是做了一个简单的应用程序,其中我从api得到一个数据,然后显示它的标题。在初始渲染时,它可以正常工作,但是每当我试图通过输入(数字)来更改值时,它就不起作用了。有人能帮我指出我的密码出了什么问题吗?蒂娅这是我代码的截图。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发布于 2020-05-04 05:25:41
在axios调用中传递initialState.id。相反,您需要将data.id作为useEffect依赖项传递,并在axios调用中传递它。
您需要在state中使用actionHandler值来获得正确的值:
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}
}
}https://stackoverflow.com/questions/61585566
复制相似问题