【问题标题】:How to properly append to string array that was passed as props in functional component如何正确附加到在功能组件中作为道具传递的字符串数组
【发布时间】:2021-05-14 16:34:18
【问题描述】:

我有一个父组件,它定义了一个字符串数组的 useState 挂钩。然后我有一个需要更新字符串数组的子组件,所以我同时传递了字符串数组和 useState 的函数来更新它。但是,当我尝试引用 props 数组时,解释器会抱怨(参见代码/cmets):

父组件.tsx:

import React, { useState } from 'react';
import { ChildComponent } from './ChildComponent';

export function ParentComponent() {
    const [log, setLog] = useState<string[]>([]);

    return(
        <ChildComponent log={log} setLog={setLog} />
    );
};

子组件.tsx

import React, { useEffect } from 'react';

interface Props {
    log: string[],
    setLog: Function
};

export function ChildComponent(props: Props) {

    useEffect(() => {

        /* I typically use this pattern to append to an array in a useState hook:

        setArray(array => [...array, "String to append"]);

        so I try to use this with the props as well: */

        props.setLog(props.log => [...props.log, "Loaded child component."]); // Interpreter complains at arrow: ',' expected. ts(1005)
    },[]);

    return (
        <div>
            {props.log.map(logItem => <p key={logItem}>{logItem}</p>)}
        </div>
    );
};

我做错了什么?

【问题讨论】:

    标签: reactjs typescript react-hooks use-state


    【解决方案1】:

    setLog: Function 不够精确。你需要:

    interface Props {
        log: string[],
        setLog: React.Dispatch<React.SetStateAction<Array<string>>>
    };
    

    还有这个

    props.setLog(props.log => [...props.log, "Loaded child component."]);
    

    应该是

    props.setLog(previousLog => [...previousLog, "Loaded child component."]);
    

    或者,在这种情况下,当这条线运行时,它看起来总是在 prop-closure 中具有日志的当前值,因此可以简化为

    props.setLog([...props.log, "Loaded child component."]);
    

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多