NextJS:子组件中获取数据并传递给父组件

aun*_*ntR 3 reactjs next.js swr

我是 Next.js 的新手,正在尝试制作一个电子商务项目。我陷入困境,如果子组件排序组件有一个到服务器的发布请求来过滤数据并将其作为产品道具传递回产品组件。

文件夹结构是这样的:

<>
 <Sort />
 <Products products={products} />
</>
Run Code Online (Sandbox Code Playgroud)

排序组件内,我会将过滤器参数发送回服务器。所以我想到的方法是使用Redux,但是我可以使用useSWRhook吗?由于操作是在排序组件中执行的,似乎useSWR钩子需要将操作和数据一起返回到同一组件中,这是正确的吗?

Pet*_*ter 9

你的代码看起来像这样:

<>
 <Sort />
 <Products products={products} />
</>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您必须在这两个容器中创建一个共享状态,如下所示:

1,您可以使用简单的共享状态,例如:

function ContainerOfTwo(props) {
  const [sharedState, setSharedState] = React.useState({});
  return (
    <>
      <Sort setSharedState={setSharedState} sharedState={sharedState} />
      <Products products={products} setSharedState={setSharedState} sharedState={sharedState} />
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

2、使用原生的 React contextAPI 或许可以与 useReducer 一起使用。(这是一个更小、更具体的状态管理。小资源

3、使用Redux。(对于更大、更 robostus 状态处理程序)

摘要:我首先会选择共享状态,如果这不足以满足您的要求,请根据您的需求使用 contextAPI 或 redux。如果你做得好,将状态保持到 contextAPI/redux 应该不是一个大问题。