使用redux in react native无法连接多个组件

时间:2018-05-24 09:29:10

标签: javascript react-native redux react-redux jsx

我无法理解如何使用redux商店连接两个不同的组件。

以下是我的尝试:

View.js

import React from 'react';
import {View, Text, Button} from 'react-native';
import {Actions} from 'react-native-router-flux';

export default ({counter,actions:{ incrementCounter}}) => (
<View>
<Text>Hello from page 1</Text>
<Button
  title='Go to page 2'
  onPress={() => Actions.page2({})}
/>
<Button
  title='Go to page 3'
  onPress={() => Actions.page3({})}
/>
<Button
  title='INCREMENT'
  onPress={() => incrementCounter()}
/>
<Text>{counter}</Text>

);

Page2.js

import React from 'react';
import { 
 View,
 Text,
 Button,
} from 'react-native';

import { Actions } from 'react-native-router-flux';
import { incrementCounter } from '../actions';

export default ({counter,actions:{ incrementCounter}}) => (
  <View>
    <Text>Hello from page2</Text>
    <Button 
      title='Go to Page 1'
      onPress={() => Actions.page1({})} />
    <Button 
      title='Go to Page 3'
      onPress={() => Actions.page3({})} />

    <Button
     title='Increment'
     onPress={() => incrementCounter()}
    />
  <Text>{counter}</Text>
  </View>

);

index.js

import React,{Component} from 'react';
import {View ,div} from 'react-native';

import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import Page1 from './View'
import Page2 from '../Page2'
import * as actionCreators from '../../actions';


class AllComp extends Component{
 render(){
     const {counter, actions} = this.props;
     return(
      <View>
       <Page1 counter={counter} actions={actions} />
       <Page2 counter={counter} actions={actions}/>
      </View>
    )
  }
}

function mapStateToProps(state){
  return{
    counter:state.counter,
  }
}

function mapDispatchToProps(dispatch){
  return{
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(AllComp);

运行代码后收到的输出有点奇怪。

它在同一页面中显示两个页面(View.js和Page2.js)的内容。

我读到要连接多个组件,我必须将这些组件包装成一个,我做了同样的事情。但正如我之前所说,输出有点奇怪。

1 个答案:

答案 0 :(得分:1)

您创建了一个包含两个页面的视图,

  <View>
   <Page1 counter={counter} actions={actions} />
   <Page2 counter={counter} actions={actions}/>
  </View>

这是两个页面在同一屏幕中显示的原因。 React-native-router-flux documentation指出应在App.js中指定路线,

const App = () => (
  <Router>
    <Stack key="root">
      <Scene key="page1" component={Page1} title="Page 1"/>
      <Scene key="page1" component={Page2} title="Page 2"/>
    </Stack>
  </Router>
);

要将多个组件连接到redux,您不必将它们包装在同一个组件中,而是必须connect使用以下函数将它们复用到必须连接的组件中。

function mapStateToProps(state){
  return{
    counter:state.counter,
  }
}

function mapDispatchToProps(dispatch){
  return{
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(Page1);