reactjs - Redux 可以在服务器端分派(dispatch)操作

标签 reactjs redux redux-thunk

我是 redux 的初学者,并创建通用的 React redux 应用程序。

这是在服务器端调度异步操作的任何选项,例如服务器端的store.dispatch(actions.getOutput())

getOutput 是一个异步操作,它在调用时获取一些 api 并更改 redux 上的状态。

我知道使用 redux-thunk 中间件在客户端分派(dispatch)它,但不了解服务器端的过程

let context = {},
    status = 200;

const allReducers = combineReducers({
    ...reducers
});

const store = createStore(
    allReducers,
    compose(
        applyMiddleware(thunkMiddleware, promise)
    )
);



    const preloadedStore = store.getState()
    store.dispatch(actions.getStories());
    const finalState = store.getState();


    const ctx = ReactDomServer.renderToString(
    <Provider store={store}>
        <StaticRouter context={context} location={req.url}>
            <App/>
        </StaticRouter>
    </Provider>
    ),
    reactHelmet = ReactHelmet.renderStatic();

    if(context.url){
        return res.redirect(302, context.url);
    }

    if(context.status === 404){
        status = 404;
    }

    let page = renderOutput(ctx, finalState, reactHelmet);
    res.status(status).send(page);

最佳答案

根据 redux-thunk 的文档,如果你像这样定义你的操作:

function makeASandwichWithSecretSauce(forPerson) {

  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

然后你就可以像这样使用它

store.dispatch(
  makeASandwichWithSecretSauce('My wife')
).then(() => {
  console.log('Done!');
});

这意味着,在服务器端你可以做

store.dispatch(makeASandwichWithSecretSauce("My wife")).then(() => {

  const ctx = ReactDomServer.renderToString(
    <Provider store={store}>
      <StaticRouter context={context} location={req.url}>
        <App />
      </StaticRouter>
    </Provider>
  );

  const reactHelmet = ReactHelmet.renderStatic();

  const page = renderOutput(ctx, finalState, reactHelmet);

  res.status(status).send(page);
});

关于reactjs - Redux 可以在服务器端分派(dispatch)操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283206/

相关文章:

reactjs - 未捕获的 TypeError : _materialUi. Styles.ThemeManager 不是函数

reactjs - react native : Unable to resolve "@ant-design/icons-react-native/fonts/antoutline.ttf"

reactjs - reducer 始终返回初始状态

redux - Redux Toolkit 中的不变性检查中间件有什么作用?

javascript - Redux:嵌套组件可以调用操作方法吗?

javascript - React Redux 调度语法

laravel - 将 Laravel Controller 中的数据注入(inject)到 React 代码中

reactjs - 未捕获的 TypeError : (0 , _reactRedux.bindActionCreators) 不是一个函数

reactjs - 将 react router V6 导航与 redux 和 redux thunk 操作一起使用的最佳方法是什么?

javascript - React Redux - 在发送问题之前快速闪现之前的状态