Javascript 在减速器中设置值时,Prop未按预期更新
我在测试新创建的action和reducer时遇到了这个问题。即使我在减速器中将道具设置为固定值,也不会更新道具 组成部分:Javascript 在减速器中设置值时,Prop未按预期更新,javascript,react-native,redux,Javascript,React Native,Redux,我在测试新创建的action和reducer时遇到了这个问题。即使我在减速器中将道具设置为固定值,也不会更新道具 组成部分: class <ComponentName> extends Component { componentDidMount() { login() } render() { if(this.props.isLogged) return (
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>)
减速器:
const initState = {
isLogged: false,
}
export default (state=initState, action) => {
switch(action.type) {
case "TEST":
return {
...state,
isLogged: true
}
break;
default:
return state
}
}
联合收割机减速器:
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>;
import React,{Component}来自“React”;
从“/app/screens/”导入
从“./app/store”导入存储
从“react redux”导入{Provider}
导出默认值()=>
;
我已经试着调试了一段时间了。我仍然不知道为什么会这样。也许我实施错了?如果有一些文件我忘了包括在内,请通知我。谢谢,祝你今天愉快 代码无法按预期工作的原因是您正在调用
login()
操作创建者,而不是从mapDispatchToProps()
返回的login()
方法(并注入
的道具中)
尝试在调用login()
之前添加this.props
来修改代码,如下所示:
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/>
}
}
类扩展组件{
componentDidMount(){
//在此处更新此行,以便login()方法
//调用connect()注入(即通过this.props)
this.props.login()
}
render(){
如果(此.props.isloged)
返回
其他的
返回
}
}
作为旁注-类扩展组件
看起来语法不正确。尝试删除
是否使用组合减速机()
?如果是的话,你能展示一下代码吗?您是否在代码中设置了断点?减速器中的开关盒是否按预期击中?@DacreDenny嗨!抱歉误解,这只是此问题的占位符值。这不是实际类的名称:Dalso,你是否用
包装了你的应用程序根组件?@DacreDenny噢,谢谢你提醒我。我会马上更新这个问题。谢谢
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/>
}
}