Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何正确地附加到函数组件中作为道具传递的字符串数组_Reactjs_Typescript_React Hooks_Use State - Fatal编程技术网

Reactjs 如何正确地附加到函数组件中作为道具传递的字符串数组

Reactjs 如何正确地附加到函数组件中作为道具传递的字符串数组,reactjs,typescript,react-hooks,use-state,Reactjs,Typescript,React Hooks,Use State,我有一个父组件,它定义了一个useState钩子,它是一个字符串数组。然后我有一个子组件需要更新字符串数组,所以我传递字符串数组和useState函数来更新它。但是,当我尝试引用props数组时,解释器会抱怨(请参阅代码/注释): ParentComponent.tsx: import React, { useState } from 'react'; import { ChildComponent } from './ChildComponent'; export function Pare

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

ParentComponent.tsx:

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

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

    return(
        <ChildComponent log={log} setLog={setLog} />
    );
};
import React,{useState}来自“React”;
从“/ChildComponent”导入{ChildComponent};
导出函数ParentComponent(){
const[log,setLog]=useState([]);
返回(
);
};
ChildComponent.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>
    );
};
import React,{useffect}来自“React”;
界面道具{
日志:字符串[],
setLog:函数
};
导出函数子组件(道具:道具){
useffect(()=>{
/*我通常使用此模式附加到useState钩子中的数组:
setArray(数组=>[…数组,“要追加的字符串”]);
所以我也试着用这些道具:*/
props.setLog(props.log=>[…props.log,“加载的子组件”。]);//解释器在箭头处抱怨:“,”预期为.ts(1005)
},[]);
返回(
{props.log.map(logItem=>

{logItem}

)} ); };

我做错了什么?

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

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

props.setLog(previousLog => [...previousLog, "Loaded child component."]);
或者,在本例中,当此行运行时,它看起来总是在prop闭包中包含日志的当前值,因此可以简化为

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