簡體   English   中英

無法在React Native中使用Redux連接多個組件

[英]Cannot connect multiple components using redux in react native

我無法理解如何將兩個不同的組件與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)的內容。

我讀到要連接多個組件,我必須將這些組件包裝成一個組件,然后做同樣的事情。 但是正如我之前所說,輸出有點奇怪。

您已經創建了一個包含兩個頁面的視圖,

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

這就是兩個頁面都顯示在同一屏幕上的原因。 React-native-router-flux 文檔指出,應在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到每個組件的以下功能connect它們connect到Redux。

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM