【问题标题】:how to set value in hooks如何在钩子中设置值
【发布时间】:2021-01-12 12:20:33
【问题描述】:

我对 ReactJS 中的钩子有疑问 正如你在这里看到的,我定义了一个应该从子组件调用的道具 但是当我想通过调用更改组件来更改值时,它不起作用并且我的状态没有设置。 有人能帮我吗? 别忘了阅读 cmets

import React, {useState} from "react";
import Collection from "./Collection";
import ReminderPeriod from "./ReminderPeriod";

function SingleReminderPage() {

    const [collection, setCollection] = useState(null);
    
    const setSelectedCollection = (e) => {
        setCollection(e);
        console.log(e); // returns the true value
        console.log(collection); // returns null
    }

    return(
        <div>
            <Collection onChoosed={(e) => setSelectedCollection(e)}/>
        </div>
    )
}

export default SingleReminderPage;

【问题讨论】:

  • 你能把Collection组件的代码贴在你调用函数的地方吗?
  • setCollection 不会同步更新状态。当这个console.log(collection); 被执行时,状态可能不会更新,这就是它仍在打印null 的原因。

标签: reactjs react-hooks components use-state


【解决方案1】:

将 setState 与回调函数一起使用

const setSelectedCollection = (e) => {
    setCollection((state)=> {...state, e});
}

setCollection(e) - 不会立即更新状态。

I want to Understand SetState and Prevstate in ReactJS

【讨论】:

    【解决方案2】:

    这可能会对你有所帮助,useEffect 将在每次集合更新时调用

    import React, { useState, useEffect } from "react";
    import Collection from "./Collection";
    import ReminderPeriod from "./ReminderPeriod";
    
    function SingleReminderPage() {
    
        const [collection, setCollection] = useState(null);
    
        useEffect(() => {
            console.log(collection)
        }, [collection])
    
        return (
            <div>
                <Collection onChoosed={(e) => setCollection(e)} />
            </div>
        )
    }
    
    export default SingleReminderPage;
    

    【讨论】:

      【解决方案3】:

      似乎在记录操作之后调用了 setCollection 以检查类似的内容,您可以在组件本身上打印集合值

      import React, {useState} from "react";
      import Collection from "./Collection";
      import ReminderPeriod from "./ReminderPeriod";
      
      function SingleReminderPage() {
      
          const [collection, setCollection] = useState(null);
          
          const setSelectedCollection = (e) => {
              setCollection(e);
              console.log(e); // returns the true value
              console.log(collection); // returns null
          }
      
          return(
              <div>
                  {collection}
                  <Collection onChoosed={(e) => setSelectedCollection(e)}/>
              </div>
          )
      }
      
      export default SingleReminderPage;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-23
        • 2020-08-04
        • 2021-09-25
        • 2021-08-02
        • 2022-10-15
        • 1970-01-01
        • 2021-03-10
        • 1970-01-01
        相关资源
        最近更新 更多