【问题标题】:Redux possibibilty to dispatch an action on server sideRedux 可以在服务器端调度操作
【发布时间】:2017-11-01 03:59:18
【问题描述】:

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

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

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

我知道使用 redux-thunk 中间件在客户端调度它,但不了解服务器端的流程

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);

【问题讨论】:

标签: reactjs redux redux-thunk


【解决方案1】:

从 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);
});

【讨论】:

  • 为什么不呢?它应该在服务器上设置状态,然后您必须将此状态传输给客户端
  • 如果你在回调中console.log(store.getState())会得到什么
  • 它打印空的初始状态。它不会更新任何状态。
  • 我认为问题出在你的减速器上!可以分享代码吗?
猜你喜欢
  • 2016-05-14
  • 2017-06-06
  • 2017-11-09
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
相关资源
最近更新 更多