在动作助手中使用 browserhostory.push 是个好主意吗?
Is it a good idea to use browserhostory.push in action helpers?
在我的 React
应用程序中,我需要根据从服务器收到的数据做出决定。
- 如果需要数据(
Dispatch actions to update state
)
- 如果数据有错误标签(
browserhistory.push('/notfound');
)
- 如果预期的数据无法解析(
browserhistory.push('/error');
)
在我的应用程序结构中,我使用了 Redux
、React-Router
和 React-redux-Router
库,但没有使用中间件。我已经让 actionHelpers 进行 ajax 调用,然后使用 Action Creator 发送适当的动作。这些 actionHelper
方法在组件中公开以更改状态。
我的问题:
- 处理这些情况的最佳方法是什么?
actionHelper
是做出这些决定的最佳地点吗?
我暂时不想使用任何中间件,但如果使用中间件来处理这些情况是个好主意,请告诉我。
操作不是您应该进行重定向的地方。此行为应在组件本身中实现,并且应保留更新商店的操作。
你可能想在这里使用 Redux-thunk middleware ,它允许你分派一个函数(它接收 dispatch
作为参数而不是对象动作。然后你可以将该函数包装在一个承诺中并在 componentWillMount
.
中使用
在您的操作文件中:
updateReduxStore(data) {
return {
type: SOME_TYPE,
payload: data.something
};
}
fetchAndValidateData() {
...
}
checkData() {
return function(dispatch) {
return new Promise((resolve, reject) => {
fetchAndValidateData().then((data) => {
try {
if (JSON.parse(data).length > 0) {
dispatch(updateReduxStore(data));
resolve('valid data');
} else if (data.error) {
reject('error in data');
}
}
catch(err) {
reject('malformed data');
}
});
});
};
}
然后在你的组件中:
componentWillMount() {
this.props.checkData()
.then((message) => {
console.log(message); //valid data
})
.catch((err) => {
if (err === 'error in data') {
browserHistory.push('/notfound');
} else if (err === 'malformed data') {
browserHistory.push('/error');
}
});
}
Redux-thunk 中间件就是为这种用例而设计的。
在我的 React
应用程序中,我需要根据从服务器收到的数据做出决定。
- 如果需要数据(
Dispatch actions to update state
) - 如果数据有错误标签(
browserhistory.push('/notfound');
) - 如果预期的数据无法解析(
browserhistory.push('/error');
)
在我的应用程序结构中,我使用了 Redux
、React-Router
和 React-redux-Router
库,但没有使用中间件。我已经让 actionHelpers 进行 ajax 调用,然后使用 Action Creator 发送适当的动作。这些 actionHelper
方法在组件中公开以更改状态。
我的问题:
- 处理这些情况的最佳方法是什么?
actionHelper
是做出这些决定的最佳地点吗?
我暂时不想使用任何中间件,但如果使用中间件来处理这些情况是个好主意,请告诉我。
操作不是您应该进行重定向的地方。此行为应在组件本身中实现,并且应保留更新商店的操作。
你可能想在这里使用 Redux-thunk middleware ,它允许你分派一个函数(它接收 dispatch
作为参数而不是对象动作。然后你可以将该函数包装在一个承诺中并在 componentWillMount
.
在您的操作文件中:
updateReduxStore(data) {
return {
type: SOME_TYPE,
payload: data.something
};
}
fetchAndValidateData() {
...
}
checkData() {
return function(dispatch) {
return new Promise((resolve, reject) => {
fetchAndValidateData().then((data) => {
try {
if (JSON.parse(data).length > 0) {
dispatch(updateReduxStore(data));
resolve('valid data');
} else if (data.error) {
reject('error in data');
}
}
catch(err) {
reject('malformed data');
}
});
});
};
}
然后在你的组件中:
componentWillMount() {
this.props.checkData()
.then((message) => {
console.log(message); //valid data
})
.catch((err) => {
if (err === 'error in data') {
browserHistory.push('/notfound');
} else if (err === 'malformed data') {
browserHistory.push('/error');
}
});
}
Redux-thunk 中间件就是为这种用例而设计的。