Ruk*_*uks 4 reactjs redux react-redux
使用可以实现的 redux-logic 比使用 redux-thunk 有什么优势?
Redux-thunk 是非常简单的(大约 10 行代码)中间件,它允许分派函数。这就是它所做的。
当调度函数时,你可以做一些其他的工作(在这个函数内),比如在调度动作之前/之后获取数据或其他东西(动作 - 意味着将直接进入减速器的对象)。
Redux-logic 是更加灵活和强大的中间件。它允许在编写代码时表达您的意图。
此示例取自文档
const fetchPollsLogic = createLogic({
// declarative built-in functionality wraps your code
type: FETCH_POLLS, // only apply this logic to this type
cancelType: CANCEL_FETCH_POLLS, // cancel on this type
latest: true, // only take latest
// your code here, hook into one or more of these execution
// phases: validate, transform, and/or process
process({ getState, action }, dispatch, done) {
axios.get('https://survey.codewinds.com/polls')
.then(resp => resp.data.polls)
.then(polls => dispatch({ type: FETCH_POLLS_SUCCESS,
payload: polls }))
.catch(err => {
console.error(err); // log since could be render err
dispatch({ type: FETCH_POLLS_FAILED, payload: err,
error: true })
})
.then(() => done()); // call done when finished dispatching
}
});
Run Code Online (Sandbox Code Playgroud)
这个示例正在获取数据,但它的意图和阶段(在这种情况下它只有一个阶段,过程)从代码中很清楚。
使用 Redux-thunk 做同样的事情会导致这样的代码
const fetchPollsLogic = () => (dispatch) => {
axios.get('https://survey.codewinds.com/polls')
.then(resp => resp.data.polls)
.then(polls => dispatch({ type: FETCH_POLLS_SUCCESS,
payload: polls }))
.catch(err => {
console.error(err); // log since could be render err
dispatch({ type: FETCH_POLLS_FAILED, payload: err,
error: true })
})
}
Run Code Online (Sandbox Code Playgroud)
代码本质上是一样的,只是缺少了声明式、分阶段等。
我可能会建议通读 redux-logic,因为它比 redux-thunk 更强大和灵活
| 归档时间: |
|
| 查看次数: |
496 次 |
| 最近记录: |