反应:在useEffect中设置输入状态不起作用

时间:2019-09-24 08:31:13

标签: reactjs react-hooks use-effect

我正在使用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 }
    });
  }
};
  

注意:如果我将 question 对象传递给useEffect挂钩依赖项   数组(如ESlint告诉我那样),输入被填充,但 GET_QUESTION 是   无限循环地调度。正如我在   Chrome中的ReduxDevToolsExtension标签

有解决这个问题的主意吗?

1 个答案:

答案 0 :(得分:1)

您需要为BE的传入响应添加其他useEffect挂钩:

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

  }, [question]);