【问题标题】:React js useReducer hook in forms controlled inputs在表单控制输入中反应 js useReducer 钩子
【发布时间】:2021-12-10 06:30:33
【问题描述】:

我在使用带有输入的 useReducer 时遇到问题。我在这里尝试使用受控输入,但我不断收到错误; 受控输入不受控制

从 "react" 导入 React, {useReducer, useEffect};

从“axios”导入axios;

常量初始状态 = {

post: {},

user: ""

} const reducer = (state, action) => {

switch(action.type){

    case "Fetch_data":

        return {

            post: action.payload

        }

    case "On_change":

        return {

            user: action.payload

        }    

    case "Fetch_error":

        return {

            post: {}

        } 

    default:

        return state  
 
}

} const ReducerFetchdata = () => {

const [info, dispatch] = useReducer(reducer, initialState)

useEffect(()=>{

    axios

        .get(`https://jsonplaceholder.typicode.com/posts/${info.user}`)

        .then (res => {

            console.log(res)

            dispatch({type: "Fetch_data", payload: res.data})

        })

        .catch(err => {

            console.log(err)

            dispatch({type: "Fetch_error"})

        })

}, [info.user])

const handleChange = (event) =>{

    dispatch({type: "On_change", payload: event.target.value})

}

return(

    <div>

        <input type="text" onChange={handleChange} value={info.user}/>

        <p>{info.post.title}</p>

    </div>

)

}

导出默认 ReducerFetchdata

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要传播整个状态,然后在从减速器返回时更新必要的键。在这种情况下,onChange 调用了 On_change,其操作没有从 reducer 状态返回 post,从而导致错误。

    参考:Sandbox for the fix

    【讨论】:

      【解决方案2】:

      只是猜测:您在获取帖子后删除了 user 键,因此 info.user 变为未定义。

      你的减速器应该是:

      switch(action.type) {
        case 'Fetch_data':
          return {
             ...state,
             post: action.payload
          }
         ...
      }
      

      总是返回

      {
         ...state
         [someKey]: someValue
      }
      

      在您的On_ChangeFetch_error 中也是如此。

      【讨论】:

        猜你喜欢
        • 2020-09-02
        • 2022-09-27
        • 2021-07-07
        • 2020-11-05
        • 1970-01-01
        • 2022-01-17
        • 2022-09-23
        • 2019-12-09
        • 1970-01-01
        相关资源
        最近更新 更多