派遣后行动道具没有改变。我的redux容器:
class ConnectedAppContent extends React.Component {
render() {
return (
<div id="content">
<Router>
<Switch>
<PropsRoute path="/login" component={LoginForm} doLogin={this.props.doLogin} />
<PrivateRoute path="/scan" redirectTo="/login" component={Scanner} token={this.props.token} />
<PrivateRoute path="/result" redirectTo="/login" component={ParsedQRCode} token={this.props.token} />
</Switch>
</Router>
</div>
);
}
}
const mapStateToProps = state => {
return {
token: state.token,
parsedQRCode: state.parsedQRCode
}
}
const mapDispatchToProps = dispatch => ({
doLogin: token => dispatch(doLogin(token))
});
export const AppContent = connect(mapStateToProps, mapDispatchToProps)(ConnectedAppContent);
和主要的App
组件一起包装到Provider
中:
export class App extends React.Component {
render() {
return (
<div className='container'>
<AppHeader />
<AppContent />
<AppFooter />
</div>
);
}
}
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.querySelector('.wrapper')
)
我应该如何更新道具?道具与初始状态绑定,但在doLogin
之后不会刷新。
已更新
我的减速器:
const initialState = {
token: null
}
export const loginReducer = (state = initialState, action) => {
switch (action.type) {
case DO_LOGIN:
return {...state, token: action.payload}
default:
return state;
}
}
和doLogin
动作:
export const doLogin = token => ({
type: DO_LOGIN,
payload: token
})
还有PrivateRoute
组件(我是从here获得的):
export const PrivateRoute = ({ component, redirectTo, ...rest }) => {
// rest.token is undefined here, even after dispatching doLogin
return (
<Route {...rest} render={routeProps => {
return !!rest.token ? (
renderMergedProps(component, routeProps, rest)
) : (
<Redirect to={{
pathname: redirectTo,
state: { from: routeProps.location }
}}/>
);
}}/>
);
};
和PropsRoute
(同样来自here):
export const PropsRoute = ({ component, ...rest }) => {
return (
<Route {...rest} render={routeProps => {
return renderMergedProps(component, routeProps, rest);
}}/>
);
}
答案 0 :(得分:2)
啊,抓住了罪魁祸首:(应该是loginReducer的令牌)
const mapStateToProps = state => {
return {
token: state.loginReducer.token,
答案 1 :(得分:1)
我假设您期望绑定到路由的token
组件上的prop Scanner
值,在这种情况下,React路由器不会将prop传递给孩子。
我不鼓励您将道具传递给路线,而是使所有路线组件成为容器组件,但是如果出于某种原因,您认为这不是将道具传递给路由器中的子项的一种方法:
<PrivateRoute path="/scan" redirectTo="/login" component={() => <Scanner token={this.props.token}>}/>