我发现了两个感觉不错的选项,并且我都使用了。我很好奇是否有人有任何问题。
选项 1:通过history
反对传奇。
它并不明显,但sagaMiddleware.run
函数采用第二个参数,该参数被转发到 sagas。 IE:
/wherever/you/start/saga.js
import { createBrowserHistory } from "history";
import saga1 from "./saga1.js";
const function* rootSaga({ history }) {
yield all([saga1({ history })])
}
const sagaTask = sagaMiddleware.run(rootSaga, { history: createBrowserHistory() });
我在这里学到了这一点:https://github.com/ReactTraining/react-router/issues/3972#issuecomment-251189856 https://github.com/ReactTraining/react-router/issues/3972#issuecomment-251189856
这是访问历史功能的一种干净的方式。在实际的传奇中,您将像平常一样使用历史对象。
./saga1.js
export default ({ history }) => [
takeEvery(actions.DO_SOMETHING_THEN_NAVIGATE, function*({ payload }) {
...do something
history.push("/somewhere");
}),
];
选项 2:使用单个 saga 来管理history
使用操作进行对象和导航
这是选项 1 的扩展。专用一个传奇来“管理”历史对象 - 使用操作推送/替换。 IE:
/my/history/saga.js
export default ({ history }) => [ // history is passed in ala option 1.
takeEvery(actions.HISTORY_PUSH, function*({ payload }) {
const pathname = payload.fooParam;
yield history.push(pathname);
}),
takeEvery(actions.HISTORY_REPLACE, function*({ payload }) {
yield history.replace({ pathname: payload.barParam });
}),
];
这可以让你的 redux 存储和操作保持干净,免受奇怪的黑客攻击some社区的提议 - 就像在行动中传递历史对象一样。
让我知道你的想法。