gpt4 book ai didi

reactjs - react : Setting input state inside useEffect not working

转载 作者:行者123 更新时间:2023-12-02 19:51:28 25 4
gpt4 key购买 nike

我正在使用 React 和 Redux 开发一个应用程序。我正在尝试使用 API 数据预填充我的输入。为此,我将 API 数据放入 useEffect 中。我也在其中设置我的状态。问题是输入未填充 API 数据。它是空的,但是当我重新加载页面时,它会被填充并且工作正常。

这是我的代码:

EditQuestion.js

const EditQuestion = ({ getQuestionById, question: { question, loading }, match: { params } }) => {
const [formData, setFormData] = useState({ title: "" });

useEffect(() => {
// Get data from API
getQuestionById(params.id);

// Populate `title` input with API Data
setFormData({
title: question !== null && question.title ? question.title : ""
});

}, [getQuestionById, params.id]); // If `question` object is passed to this dependency array, `GET_QUESTION` is dispatched in an infinite endless loop

const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });

const onSubmit = e => {};

const { title } = formData;

return (
<form onSubmit={e => onSubmit(e)}>
<input
type="text"
name="title"
placeholder="e.g How to encrypt a string in C"
value={title}
onChange={e => onChange(e)}
/>
<input type="submit" value="Ask question" />
</form>
);
};

EditQuestion.propTypes = {
getQuestionById: PropTypes.func.isRequired,
question: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
question: state.question
});

export default connect(
mapStateToProps,
{ getQuestionById }
)(EditQuestion);

question.js(操作)

// Get question by ID
export const getQuestionById = id => async dispatch => {
try {
const res = await axios.get(`/api/question/${id}`);

dispatch({
type: GET_QUESTION,
payload: res.data
});
} catch (err) {
dispatch({
type: QUESTION_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};

NOTE: If i pass the question object to useEffect hook dependency array (As ESlint is telling me to do so), input gets populated but the GET_QUESTION is dispatched in an infinite endless loop. As i've seen in the ReduxDevToolsExtension tab in chrome

有办法解决这个问题吗?

最佳答案

您需要为来自 BE 的传入响应添加额外的 useEffect Hook :

useEffect(() => {
// Populate `title` input with API Data
setFormData({
title: question !== null && question.title ? question.title : ""
});

}, [question]);

关于reactjs - react : Setting input state inside useEffect not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com