繁体   English   中英

React Axios - 未列出获取的数据

[英]React Axios - The fetched data is not listed

我正在使用 Axios 发送数据和获取数据。 数据来了,我可以用console.log(res.data)看到,但是我不能把res.data应用到setMessages

  const [formData, setFormData] = useState({ input: null });

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData({ input: e.target.value });

  const onSubmit = event => {
    event.preventDefault();
    const data = new FormData(event.target);
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });

    axios
      .post(`http://localhost:4000/prediction`, (data: data), {
        crossdomain: true
      })
      .then(res => {
        console.log(res.data);
        setMessages(prevMsgs => [...prevMsgs, res.data]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };

在您的代码中,您直接执行异步操作。 要在功能组件中执行异步操作,应根据挂载/更新要求使用“useEffect”钩子。

就像在类组件中异步操作是从 componentDidMount 生命周期事件方法执行的,useEffect 钩子是功能组件中 componentDidMount、componentDidUpdate 和 componentWillUnmount 的后继者。

componentDidMount 等效于 React 函数/Hooks 组件吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM