React - 数组作为它们的长度传递

时间:2021-01-11 18:03:50

标签: arrays reactjs react-hooks use-effect

我是新来的,我正在尝试为我的项目使用钩子。 我需要将一个数组从父级传递给子级,当我将数组放入 props 时,它只会传递它的长度。

ParentComponent.js
export default function NewHome() {

const [isReady, setReadyState] = useState(false);

const [regionWithValue, setRegionWithValue] = useState([]);


function getRegion() {
    fetch("http://localhost:3000/region")
        .then(res => res.json())
        .then(
            (result) => {
                result.forEach((el) => {
                    setRegionWithValue(regionWithValue.push(el));
                })
                setReadyState(true);
            },
            (error) => {
                setErrore(true);
            }
        );
};
useEffect(() => {
    getRegion();
    console.log(regionWithValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
},[]);
if (ReadyState) {
console.log(regionWithValue);
return(
<ChildComponent region={regionWithValue}/>
)
}

useEffect() 中的console.log 实际上打印了正确的数组并获取了数据,但是返回之前的第二个console.log 只是打印出数组大小,因此我无法将其传递给ChildComponent。我不知道是否是生命周期的原因,所以我都错了。谢谢。

2 个答案:

答案 0 :(得分:0)

这就是问题所在:

setRegionWithValue(regionWithValue.push(el));

push 返回长度而不是您推送到的数组

你可以这样做:

setRegionWithValue(v => ([...v, el]));

见:Why does Array.prototype.push return the new length instead of something more useful?

来自Array.prototype.push() MDN docs的声明:

<块引用>

push() 方法在数组末尾添加一个或多个元素并返回数组的新长度。

答案 1 :(得分:-1)

你不能在 React Hook 上使用 push。您需要获取以前的状态并添加到该状态(prevState 是行业标准命名约定)。这可以在您的 fetch 中完成,如下所示:

    setRegionWithValue(prevState => (
          setRegionWithValue([...prevState, result])
        ));

这将始终添加到状态中,如果您只想在每次获取时创建一个新状态,那么您应该使用:

setRegionWithValue(result)