![](/img/trans.png)
[英]How can i get setState to work in an event handler in a functional React component
[英]React functional component : can we setState on form load event
用鈎子反應組件:
要求:當頁面加載時,數據從后端填充到下拉列表和多選表(帶有復選框的表)中。 在提交按鈕上單擊,我需要使用它合並 object(對於選擇的默認值)來進行另一個 REST 調用。
注意:沒有為這些 ui 組件調用任何更改處理程序。
問題:
需要的建議:有沒有辦法在表單加載事件中設置默認選定值的狀態。
const [data, setData] = useState(undefined);
const changeRequests = useSelector(state =>
state.oncallRequest.changeRequests
);
useEffect(() => {
if (!changeRequests.fulfilled) {
dispatch(fetchRequests(), [dispatch])
.then(response => setData(setDefaultState(response.data)));
}
}, [changeRequests.fulfilled, dispatch]);
我收到以下錯誤:
ERROR: TypeError: Cannot read property 'then' of undefined.async call.
動作 Class:
export const fetchRequests = () => dispatch => {
dispatch({type: LIST_PENDING});
listChangeRequests().then(data => {
dispatch({type: LIST_FULFILLED, changeRequests: data})
}).catch(err => {
dispatch({type: LIST_FAILED, changeRequests: {error: err.message}})
});
};
**Service Class**
export const listChangeRequests = () => axiosInstance.get(`/getData`).then(res => {
return res.data;
});
SOLUTION:
I used 2 use Effect: one for fetching data from backend and another for setting state.
**but getting the following exception**
1) **React Hook useEffect has a missing dependency: 'setDefaultState'. Either include it or remove the dependency array**
2) 'data' is assigned a value but never used
Please advise on the warnings...
useEffect(() => {
if (!changeRequests.fulfilled) {
dispatch(fetchRequests(), [dispatch])
}
}, [changeRequests.fulfilled, dispatch]);
-------------
useEffect(() => {
if (changeRequests.data) {
setData(setDefaultState(changeRequests.data));
}
}, [changeRequests.data]);
很可能,您不知道useEffect
,在最初安裝組件時useEffect
可以調用 API ,然后使用useState
。 如下所示:
import React, { useState, useEffect } from 'react';
const FormComponent = () => {
const [data, setData] = useState(undefined);
const [error, setError] = useState(undefined);
useEffect(() => {
// call an API and in the success or failure fill the data buy using setData function
// it could be like below
ApiCall()
.then(response => setData(response))
.catch(err => setError(err))
}, []);
~~~
};
更新
這部分是在您添加代碼后添加的。 實際上,您的dispatch
function 不返回Promise
事件不返回任何內容。 所以在你的代碼中使用then
是不可接受的,JavaScript 解釋器應該返回一個錯誤。 我想你應該專注於你的dispatch
function。
這是從 api 獲取數據的完整示例。 請檢查一下。 希望它可以幫助你。
import React, { useEffect, useState } from "react";
import axios from "axios";
function ExamplePost() {
const [isLoading, setIsLoading] = useState(false);
const [posts, setPosts] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
onLoadUser();
}, []);
function onLoadUser() {
try {
setIsLoading(true);
const response = axios.get(`https://jsonplaceholder.typicode.com/posts`, {
cancelToken: this.signal.token
});
response
.then((response) => {
setPosts(response);
setIsLoading(false);
})
.catch((error) => {
setError(error);
setIsLoading(false);
});
} catch (error) {
setIsLoading(false);
}
}
return (
<div>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default ExamplePost;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.