如何在钩子中设置值

Posted

技术标签:

【中文标题】如何在钩子中设置值【英文标题】: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 的原因。 【参考方案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;

【讨论】:

以上是关于如何在钩子中设置值的主要内容,如果未能解决你的问题,请参考以下文章

如何在下拉菜单中设置值

如何以角度在 FormArray 中设置值?

如何根据索引在数据框中设置值[重复]

如何使用 QtActive 在单元格中设置值

如何在 extjs 3.2 中设置值

我如何等待在柏树中设置值?