【问题标题】:Function passing null at first run首次运行时传递 null 的函数
【发布时间】:2021-08-03 15:32:27
【问题描述】:

我在将数据传递到 JSON 文件时遇到了一点问题。我有一个运行onClick 的函数。第一次运行返回:

{
   "title": "",
   "description": "",
   "price": "",
   "id": 1
}

但所有下一次运行都正确返回数据:

{
   "title": "Example title",
   "description": "Example description",
   "price": "$7",
   "id": 2
}

有人知道怎么解决吗?

我的反应代码:

    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [price, setPrice] = useState('');

    const addToCart = (e) => {
        e.preventDefault();
        setTitle('Example title');
        setDescription('Example description');
        setPrice('$' + Math.floor(Math.random() * 10 + 1));

        const product = { title, description, price};

        fetch('http://localhost:8000/basket', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(product)
        })
        .catch((err) => {
            console.log(err.message);
        })
    }

【问题讨论】:

    标签: json reactjs fetch


    【解决方案1】:

    因为 setState 是异步的,并且仅在组件重新渲染时更新。因此,您可以声明要在 post 和 setState 中使用的变量。

    const addToCart = (e) => {
      e.preventDefault();
    
      const product = {
        title: "Example title",
        description: "Example description",
        price: "$" + Math.floor(Math.random() * 10 + 1),
      };
    
      setTitle(product.title);
      setDescription(product.description);
      setPrice(product.price);
    
      fetch("http://localhost:8000/basket", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(product),
      }).catch((err) => {
        console.log(err.message);
      });
    };
    

    【讨论】:

      【解决方案2】:

      它可能会中断,因为您在进行 fetch 调用时尝试在初始空状态值上设置状态。这里的设计是错误的,您不应该在进行 fetch 调用时分配硬编码状态。

      const Form = () => {
        const [value, setValue] = useState('')
      
        const submit = () => {
          // make fetch call here using value
        }
      
        return <form onSubmit={(e) => {e.preventDefault(); submit()}}>
          <input type='text' value={value} onChange={(e) => setValue(e.target.value)}
        </form>
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-23
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-30
        • 1970-01-01
        相关资源
        最近更新 更多