我刚刚熟悉redux并且已经阅读了我应该通过app的父级传递动作创建者,并通过mapStateToProps,mapDispatchToProps和connect函数我应该能够传递动作。但是,当我调用子组件this.props时。该函数不存在,因此似乎没有正确传递。
我非常感谢你的帮助。
注意:我省略了一些东西,比如import和reducer更简洁。
login.js:
export function login(token, id) {
console.log('login action');
return {
type: 'LOG_IN',
token,
id,
};
}
index.ios.js:
import * as actionCreators from './actions/login'
const store = createStore(RootReducer, undefined, autoRehydrate());
persistStore(store);
class App extends Component {
constructor(props) {
super(props);
state = {
token: '',
id: '',
store: store,
};
}
render() {
return (
<Provider store={ state.store }>
<View style = {styles.container}>
<LoginView/>
</View>
</Provider>
);
}
}
AppRegistry.registerComponent('App', () => App);
function mapStateToProps(state) {
return {
token: state.token,
id: state.id
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({actionCreators}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
loginView.js:
export class LoginView extends View {
static propTypes = {}
static defaultProps = {}
constructor(props) {
console.log(props);
super(props)
this.state = {
user: '',
token: '',
id: '',
}
this.onLogin = this.onLogin.bind(this);
}
onLogin() {
console.log("on login1");
this.props.login({token: this.state.token, id: this.state.id});
console.log("on login");
}
基本上发生的事情是当onLogin()函数直接在上面引发时,它声明this.props.login不是函数。这是什么原因,我该如何解决?
答案 0 :(得分:2)
您正在连接App组件,因此会有this.props.onLogin()
。但是,您并未将onLogin
作为道具传递给<LoginView />
。您需要呈现<LoginView onLogin={this.props.onLogin} />
,或者还要连接LoginView并将onLogin
包含在该组件的连接中。
答案 1 :(得分:2)
这一行:
return bindActionCreators({actionCreators}, dispatch);
应该是:
return bindActionCreators(actionCreators, dispatch);
&#34; actionCreators&#34;已经是一个对象了。通过将其传递到另一组花括号中,它被解释为ES6速记属性名称的语法。你实际传递的是一个看起来像这样的新对象:
{
actionCreators: {
login: ... // your action is buried here
}
}
// ^^ which would get mapped to this.props.actionsCreators.login (wrong)
答案 2 :(得分:0)
似乎redux connect in native native to binding state in the days of the days is use
import {connect} from "react-redux";
...
class HomeScreen extends React.Component {
// do your things..
constructor(props) {
super(props);
console.log(this.props);
}
render () {
....
}
}
const mapStateToProps = state => {
return { user: state.user };
};
export default connect(mapStateToProps)(HomeScreen);