我在测试我新创建的 action 和 reducer 时遇到了这个问题。即使我在我的 reducer 中将其设置为固定值,prop 也不会更新。
组件:
class <ComponentName> extends Component {
componentDidMount() {
login()
}
render() {
if(this.props.isLogged)
return (
<App/>
);
else
return (
<ErrorScreen/>
);
}
}
function mapStateToProps(state) {
return {
isLogged:state.auth.isLogged
}
}
const mapDispatchToProps = (dispatch) => {
return {
login: () => dispatch(login())
};
};
export default connect(mapStateToProps,mapDispatchToProps)(<ComponentName>)
行动:
export function login() {
return {
type:"TEST"
}
}
reducer :
const initState = {
isLogged: false,
}
export default (state=initState, action) => {
switch(action.type) {
case "TEST":
return {
...state,
isLogged: true
}
break;
default:
return state
}
}
联合 reducer :
import {combineReducers} from 'redux'
import AuthenticationReducer from './authenticationReducer'
export default combineReducers({
auth: AuthenticationReducer
})
提供者:
import React, {Component} from "react";
import <ComponentName> from './app/screens/<ComponentName>'
import store from './app/store'
import {Provider} from 'react-redux'
export default () =>
<Provider store={store}>
<<ComponentName>/>
</Provider>;
一段时间以来一直在尝试调试它。我仍然不知道为什么会这样。也许我错误地实现了它?如果有一些我忘记包含的文件,请通知我。谢谢,祝你有美好的一天!
最佳答案
您的代码未按预期工作的原因是因为您正在调用 login()
Action 创造者,而不是 login()
从 mapDispatchToProps()
返回的方法(并注入(inject)到 props
的 <ComponentName/>
中)。
尝试通过添加 this.props
来修改您的代码在您调用 login()
之前像这样:
class <ComponentName> extends Component {
componentDidMount() {
// Update this line here so that the login() method
// injected by connect() is called (ie via this.props)
this.props.login()
}
render() {
if(this.props.isLogged)
return <App/>
else
return <ErrorScreen/>
}
}
关于javascript - 在 reducer 中设置值时,Prop 未按预期更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292632/