是否可以在特定路由上调用称为thunk
的异步redux操作,并且在响应成功或失败之前不执行转换?
使用案例
我们需要从服务器加载数据并使用初始值填充表单。在从服务器获取数据之前,这些初始值不存在。
这样的语法会很棒:
<Route path="/myForm" component={App} async={dispatch(loadInitialFormValues(formId))}>
答案 0 :(得分:11)
回答阻止过渡到新路线的原始问题,直到回复成功或失败为止:
因为你正在使用redux thunk,你可以在动作创建器中成功或失败触发重定向。我不知道你的具体动作/动作创建者是什么样的,但是这样的事情可以起作用:
import { browserHistory } from 'react-router'
export function loadInitialFormValues(formId) {
return function(dispatch) {
// hit the API with some function and return a promise:
loadInitialValuesReturnPromise(formId)
.then(response => {
// If request is good update state with fetched data
dispatch({ type: UPDATE_FORM_STATE, payload: response });
// - redirect to the your form
browserHistory.push('/myForm');
})
.catch(() => {
// If request is bad...
// do whatever you want here, or redirect
browserHistory.push('/myForm')
});
}
}
跟进。在输入路径/组件的componentWillMount并显示微调器时加载数据的常见模式:
来自异步操作http://redux.js.org/docs/advanced/AsyncActions.html
上的redux文档
- 通知减压者请求开始的动作。
reducers可以通过切换isFetching标志来处理这个动作 国家。这样UI就知道是时候展示一个微调器了。
- 通知减压器请求已成功完成的操作。
Reducer可以通过将新数据合并到中来处理此操作 状态他们管理和重置isFetching。用户界面会隐藏 微调器,并显示获取的数据。
- 通知减压器请求失败的操作。
reducers可以通过重置isFetching来处理这个动作。 此外,一些Reducer可能希望存储错误消息,所以 用户界面可以显示它。
我使用您的情况作为粗略的指导方针,遵循以下这种一般模式。您不必使用承诺
// action creator:
export function fetchFormData(formId) {
return dispatch => {
// an action to signal the beginning of your request
// this is what eventually triggers the displaying of the spinner
dispatch({ type: FETCH_FORM_DATA_REQUEST })
// (axios is just a promise based HTTP library)
axios.get(`/formdata/${formId}`)
.then(formData => {
// on successful fetch, update your state with the new form data
// you can also turn these into their own action creators and dispatch the invoked function instead
dispatch({ type: actions.FETCH_FORM_DATA_SUCCESS, payload: formData })
})
.catch(error => {
// on error, do whatever is best for your use case
dispatch({ type: actions.FETCH_FORM_DATA_ERROR, payload: error })
})
}
}
// reducer
const INITIAL_STATE = {
formData: {},
error: {},
fetching: false
}
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_FORM_DATA_REQUEST:
// when dispatch the 'request' action, toggle fetching to true
return Object.assign({}, state, { fetching: true })
case FETCH_FORM_DATA_SUCCESS:
return Object.assign({}, state, {
fetching: false,
formData: action.payload
})
case FETCH_FORM_DATA_ERROR:
return Object.assign({}, state, {
fetching: false,
error: action.payload
})
}
}
// route can look something like this to access the formId in the URL if you want
// I use this URL param in the component below but you can access this ID anyway you want:
<Route path="/myForm/:formId" component={SomeForm} />
// form component
class SomeForm extends Component {
componentWillMount() {
// get formId from route params
const formId = this.props.params.formId
this.props.fetchFormData(formId)
}
// in render just check if the fetching process is happening to know when to display the spinner
// this could also be abstracted out into another method and run like so: {this.showFormOrSpinner.call(this)}
render() {
return (
<div className="some-form">
{this.props.fetching ?
<img src="./assets/spinner.gif" alt="loading spinner" /> :
<FormComponent formData={this.props.formData} />
}
</div>
)
}
}
function mapStateToProps(state) {
return {
fetching: state.form.fetching,
formData: state.form.formData,
error: state.form.error
}
}
export default connect(mapStateToProps, { fetchFormData })(SomeForm)
答案 1 :(得分:2)
首先,我想说有is a debate around使用react-router的onEnter
挂钩获取数据的主题,无论是否良好做法,不过这是怎么会这样:
您可以将redux-store传递给Router
。让以下内容成为您安装Router
的根组件:
...
import routes from 'routes-location';
class Root extends React.Component {
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<Router history={history}>
{ routes(store) }
</Router>
</Provider>
);
}
}
...
您的路线将是:
import ...
...
const fetchData = (store) => {
return (nextState, transition, callback) => {
const { dispatch, getState } = store;
const { loaded } = getState().myCoolReduxStore;
// loaded is a key from my store that I put true when data has loaded
if (!loaded) {
// no data, dispatch action to get it
dispatch(getDataAction())
.then((data) => {
callback();
})
.catch((error) => {
// maybe it failed because of 403 forbitten, we can use tranition to redirect.
// what's in state will come as props to the component `/forbitten` will mount.
transition({
pathname: '/forbitten',
state: { error: error }
});
callback();
});
} else {
// we already have the data loaded, let router continue its transition to the route
callback();
}
}
};
export default (store) => {
return (
<Route path="/" component={App}>
<Route path="myPage" name="My Page" component={MyPage} onEnter={fetchData(store)} />
<Route path="forbitten" name="403" component={PageForbitten} />
<Route path="*" name="404" component={PageNotFound} />
</Route>
);
};
请注意你的路由器文件正在以你的商店为参数导出thunk,如果你向上看,看看我们如何调用路由器,我们将商店对象传递给它。
可悲的是,在撰写本文时react-router docs将404返回给我,因此我无法向您指出描述(nextState, transition, callback)
的文档。但是,关于那些,从我的记忆中来看:
nextState
描述了路由react-router
将转换为;
transition
函数可以执行另一个转换,而不是来自nextState
的转换;
callback
会触发您的路线转换完成。
另一个想法指出,使用redux-thunk,您的调度操作可以返回一个承诺,请在文档here中进行检查。您可以在here上找到有关如何使用redux-thunk配置redux商店的一个很好的示例。
答案 2 :(得分:1)
我为此目的制作了一个方便的钩子,适用于 react-router v5:
/*
* Return truthy if you wish to block. Empty return or false will not block
*/
export const useBlock = func => {
const { block, push, location } = useHistory()
const lastLocation = useRef()
const funcRef = useRef()
funcRef.current = func
useEffect(() => {
if (location === lastLocation.current || !funcRef.current)
return
lastLocation.current = location
const unblock = block((location, action) => {
const doBlock = async () => {
if (!(await funcRef.current(location, action))) {
unblock()
push(location)
}
}
doBlock()
return false
})
}, [location, block, push])
}
在你的组件中,像这样使用它:
const MyComponent = () => {
useBlock(async location => await fetchShouldBlock(location))
return <span>Hello</span>
}
在异步函数返回之前不会发生导航;您可以通过返回 true
来完全阻止导航。
答案 3 :(得分:0)
由于以下错误,现在browserHistory
不起作用:
'browserHistory'不会从'react-router'导出。
改为使用此代码:
import { createHashHistory } from 'history'
const history = createHashHistory()
并使用
this.props.history.push('/some_url')
在您的fetch
上或其他任何地方。