如何在 Next JS 中共享 redux state 客户端和 props 服务器端

Trí*_*Lâm 0 reactjs react-redux next.js

我是 Next JS 的新手

我使用Next JSRedux

我有一个简短的代码如下:

const AdminContainer = (props) => {
  
  return (
    <AdminMasterView>
      <DashboardView studentList={props.studentListServer}/>
    </AdminMasterView>
  )
}

export const getStaticProps = (async () => {

  let response = await db.getInstance().query('SELECT * FROM student_register;');

  return {
    props: {
      studentListServer: response
    }, // will be passed to the page component as props
  }
})

const mapStateToProps = state => ({
  studentList: state.studentInfoReducers.studentList
});

const mapDispatchToProps = {
  getStudentRegisterAction
};

export default connect(mapStateToProps, mapDispatchToProps)(AdminContainer);
Run Code Online (Sandbox Code Playgroud)

我还在ReduxstudentList中声明了(数组类型) props 。我想用它来传递数据,因为我有很多任务需要处理数据,例如过滤器、订单......

有什么方法可以studentList像这样使用,而我的应用程序仍然是第一次服务器渲染。

如果我发送studentListServerstudentList,它仍然有效。但我的应用程序不是服务器渲染。

<DashboardView studentList={props.studentList}/>
Run Code Online (Sandbox Code Playgroud)

或者更简单的是,我将检查对客户端使用 props.studentList ,对服务器端使用 props.studentListServer 。但我觉得这样不好。

太感谢了!

小智 6

您可以使用next-redux-wrapper包。它允许在服务器和客户端上同步 Redux 状态。考虑这个例子:

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
  let response = await db.getInstance().query('SELECT * FROM student_register;');

  // dispatch the action that saves the data
  store.dispatch({ type: 'SET_STUDENTS', payload: response });

  return {
    props: {
      studentListServer: response
    }, // will be passed to the page component as props
  }
})
Run Code Online (Sandbox Code Playgroud)

wrapper.getStaticPropsgetStaticProps用新参数包装你的函数store,这个新参数实际上是一个 Redux 存储。

SET_STUDENTS类型的操作在服务器端设置学生列表。当 Next.js 生成页面时,它将将此数据保存在静态 JSON 中。因此,当页面在客户端打开时,next-redux-wrapper会重新创建状态调度 HYDRATE操作,并保存在构建时静态 JSON 中,您可以使用该静态 JSON 来恢复studentInfoReducers减速器。

例如,在你的减速器中你应该实现类似的东西:

import { HYDRATE } from 'next-redux-wrapper';

const initialState = { studentList: [] };

// studentInfoReducers reducer
function reducer(state = initialState, action) {
  // this sets your student list
  if (action.type === 'SET_STUDENTS') {
    return {
      ...state,
      studentList: action.payload,
    };
  }
  
  // this rehydrates your store from server on a client
  if (action.type === HYDRATE) {
    return action.payload.studentInfoReducers;
  }

  return state;
}
Run Code Online (Sandbox Code Playgroud)

因此,之后您应该同时在客户端和服务器上拥有有效的同步状态:

const mapStateToProps = state => ({
  studentList: state.studentInfoReducers.studentList // works on server and client
});
Run Code Online (Sandbox Code Playgroud)

如果您有任何疑问,请告诉我,next-redux-wrapper乍一看可能会很棘手。