从 redux 分派完成后的调用函数 [英] Call function after dispatch from redux has finished
问题描述
围绕它,但不完全是因为我对 redux-thunk
和 react-router
有足够的了解,但我没有得到这个看似简单的想法:
在动作完成分派到商店后,通过<Route/>
的history.push('/')
以编程方式调用路由的更改,按下按钮时会发生这种情况.
const LoggerRedux = ({stateProp, LogIn}) =>{返回(<div><h2>这是按钮.使用它登录<路由渲染={({历史})=>(<按钮类型='按钮'点击={//调用{LogIn}的东西//然后history.push('/')}>日志哟屁股旅馆按钮>)}></路线>
)}const mapStateToProps = (状态) =>{返回 {stateProp : 状态}}const mapDispatchToProps = (调度) =>{返回 {登录:() =>派遣({类型:'认证'}),注销:(布尔)=>派遣({类型:'LOGGED_OUT',布尔值})}}const LoginConn = connect(mapStateToProps, mapDispatchToProps)(LoggerRedux);
我提到/标记的所有事物的外行解释和示例也很好
让你的动作创建者返回一个承诺.这样,当您调用它时,您可以使用 .then() 并且在您的 then 处理程序中,您可以将新地址推送到历史记录中.
Thunks 会正常返回函数,但 promise 的不同之处在于你可以在完成后采取行动.
示例:
static myActionCreator(somevar) {返回调度 =>{返回新的承诺((解决,拒绝)=> {派遣({类型:我的行动",东西:somevar});解决()});}}
所以在这种情况下,你的 thunk 返回一个 promise.然后当你这样调用时:
this.props.myActionCreator(somevar).then(() => {this.props.history.push('/获胜')})
这个 thunk 只是调度一个动作,但你可以在那里有一些异步调用,有回调等,你在完成时解决.
All around it but not quite as I have enough of an idea of redux-thunk
and of react-router
but I am not getting this seemingly simple idea of:
Call a change in route programmatically via <Route/>
's history.push('/')
after an action has finished dispatching to the store, this to happen when a button is pushed.
const LoggerRedux = ({stateProp, LogIn}) => {
return(
<div>
<h2>Here is the button. Use this to login</h2>
<Route render={({ history}) => (
<button
type='button'
onClick={
//Something that calls {LogIn}
//and then the history.push('/')
}
>
Log yo Arse Inn
</button>
)}>
</Route>
</div>
)
}
const mapStateToProps = (state) => {
return {
stateProp : state
}
}
const mapDispatchToProps = (dispatch) => {
return {
LogIn : () => dispatch({
type : 'AUTHENTICATE'
}),
LogOut : (bool) => dispatch({
type : 'LOGGED_OUT',
bool
})
}
}
const LoginConn = connect( mapStateToProps, mapDispatchToProps)(LoggerRedux);
Layman explanations and examples of all things I mentioned/tagged would also be nice
Have your action creator return a promise. This way when you invoke it, you can use .then() and in your then handler you can push a new address to the history.
Thunks will return functions normally, but a promise differs in that you can act after completion.
Example:
static myActionCreator(somevar) {
return dispatch => {
return new Promise((resolve, reject) => {
dispatch({
type: "myaction",
something: somevar
});
resolve()
});
}
}
So in this case, your thunk returns a promise. Then when you invoke like this:
this.props.myActionCreator(somevar)
.then(() => {
this.props.history.push('/winning')
})
This thunk is just dispatching an action, but you could have some async call in there that has a callback, etc. and you resolve on completion.
这篇关于从 redux 分派完成后的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!