我刚刚熟悉 redux,并且一直在阅读我应该通过应用程序的父级传递操作创建者,并通过 mapStateToProps、mapDispatchToProps 和 connect 函数我应该能够传递操作。但是,当我调用子组件 this.props 时。该函数不存在,因此看起来它没有被正确传递。
非常感谢您的帮助。
注意:为了更加简洁,我省略了一些内容,例如导入和 reducer 。
登录.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 不是一个函数。造成这种情况的原因是什么以及如何解决?
最佳答案
您正在连接应用程序组件,因此将有 this.props.onLogin()
。但是,您没有通过 onLogin
作为<LoginView />
的支撑。您需要渲染 <LoginView onLogin={this.props.onLogin} />
,或者也连接 LoginView 并包含 onLogin
作为该组件连接的一部分。
关于javascript - React Native 连接函数不通过 props 将操作传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538619/