10

我有一个包含多个组件的文件,我想导出并连接到 redux,我该怎么做?

连接包装器需要导出默认值,但我有多个组件。

4

2 回答 2

15

您不必导出默认值即可使用连接。您可以在同一个文件中连接多个组件,无论是否导出它们。虽然我建议每个文件只放置 1 个组件

import React from 'react'
import { connect } from 'react-redux'

// This also works without the export statement
export const Comp1 = connect(
    state => ({
        someProp: state,
    })
)(({ someProp }) => (
    <div>
        <h1>Comp 1</h1>
        <p></p>
    </div>
))

const Comp2 = connect(
    state => ({
        someProp: state,
    })
)(({ someProp }) => (
    <div>
        <h1>Comp 2</h1>
        <p></p>
    </div>
))

export default Comp2
于 2019-04-06T07:10:17.970 回答
-1

redux不提供任何默认导出。react-redux始终在需要时使用连接到 redux 。
如果你想通过父组件传递你的子组件,然后连接dispatch你的父组件,然后连接子组件。然后全部可用在父组件和子组件上。statereduxdestructurepropsdispatchstate

import React from 'react'
import { connect } from 'react-redux'
import Component1 from './component1'
import Component2 from './component2'
import { sampleDispathFunction } from './actions'

const WrapperComponent = (props) => {

  return <div>
    <Component1 {...props} />
    <Component2 {...props} />
  </div>
}

const mapStateToProps = (state) => ({
  data: state.data,
  customer: state.customer
});
const mapDispatchToProps = (dispatch) => ({
  sampleDispathFunction: (data) => dispatch(sampleDispathFunction(data))
});
export default connect(mapStateToProps, mapDispatchToProps)(WrapperComponent);
于 2019-04-07T06:16:15.803 回答