父子组件之间的共享状态

Shared state between Parent and Child component

我正在 Next.js 建立战线。我将一个组件嵌套在另一个组件中,我希望这两个组件共享一个 ID 数组。

主要组件是一个页面,允许用户创建一个包含他的一些 post 的集合。它发送带有 collection_name 和 array_of_ids.

的 post 请求

嵌套在页面中的另一个组件显示用户的所有 post。我创建了另一个组件,因为我在其他一些页面中需要它。

我希望用户能够通过单击 select 显示在嵌套组件中的 post,并在主组件中获取它们的 ID。

主要成分:

const CreateCollection() => {

    const [collectionIds, setCollectionIds] = useState([]);

    /* rest of the state, post request*/ 

    return( 
        ...
        <Myposts collectionIds={collectionIds}, setCollectionIds={setCollectionIds}/>
        ...
        )}

嵌套组件:

export default function Myposts ({setCollectionIds, collectionIds}){

    const addId = (newId) =>{
        setCollectionIds(collectionIds.push(newId))  
    }

    /* rest of the state, get request*/ 

    return( 
        ...
        <div>
            {Posts.map((post) => (
                        <div key={post.id}
                            value={post.id}
                            onClick={addId(post.id)}
                        >
                            {post}</div>))}
        </div>
        ...
        )}

每当我从我的嵌套组件添加一个 Id 时,我都会收到一条错误消息,指出“Posts.map... 不是一个函数”,并且我没有在我的主要组件中取回数组。

我还在学习 Next 所以我现在有点困惑我应该如何处理!

谢谢!

setCollectionIds(collectionIds.push(newId))  

Array.push 返回的不是数组而是数组的长度

const array = [1]
console.log(array.push(2)) // prints 2 because array.length is 2

你实际上是将状态设置为数字,而不是数组,你可以这样做:

setCollectionIds([...collectionIds, newId])  

setCollectionIds(collectionIds.concat([newId]))