[英]React native connect function not passing action to child component through props
我剛剛熟悉Redux,並且已經閱讀到我應該通過應用程序的父級,mapStateToProps,mapDispatchToProps和connect函數傳遞動作創建者,我應該能夠傳遞動作。 但是,當我調用子組件this.props時。 該函數不存在,因此似乎未正確傳遞它。
我將不勝感激。
注意:為簡化起見,我省略了一些東西,例如進口和減速器。
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不是函數。 這是什么原因,我該如何解決?
您正在連接App組件,因此將具有this.props.onLogin()
。 但是,您沒有將onLogin
傳遞給<LoginView />
的道具。 您需要呈現<LoginView onLogin={this.props.onLogin} />
,或者也連接LoginView並將onLogin
作為該組件連接的一部分包括onLogin
。
這行:
return bindActionCreators({actionCreators}, dispatch);
應該:
return bindActionCreators(actionCreators, dispatch);
“ actionCreators”已經是一個對象。 通過將其傳遞到另一組花括號中,它被解釋為ES6速記屬性名稱的語法。 您實際傳遞的是一個新對象,如下所示:
{
actionCreators: {
login: ... // your action is buried here
}
}
// ^^ which would get mapped to this.props.actionsCreators.login (wrong)
似乎在使用這些天的組件中,redux connect in react native綁定狀態
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.