javascript - React Native 连接函数不通过 props 将操作传递给子组件

标签 javascript reactjs react-native redux react-redux

我刚刚熟悉 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/

相关文章:

javascript - 视频捕获期间移动 safari 内存不足

ios - 调用 React Native App 接收来自浏览器的共享信息

javascript - 对象键 'undefined'

javascript - 如何在javascript中执行旋转变换?

javascript - 如何将 v-for 计算数据作为参数发送到 Vue.js 上运行?

javascript - 通过事件处理程序更改 React 状态

javascript - 即使调用了 React 组件方法,expect(...).toHaveBeenCalled() 也会失败

javascript - componentDidCatch + window.addEventListener ('error' , cb) 行为不符合预期

ios - React Native 无法构建示例项目(XCode 8.1/Sierra)

javascript - 注销后 React Router 4 管理路由