Passing props to react-redux container component

后端 未结 4 1731
温柔的废话
温柔的废话 2021-01-30 05:08

I have a react-redux container component that is created within a React Native Navigator component. I want to be able to pass the navigator as a prop to this container component

相关标签:
4条回答
  • 2021-01-30 05:26

    You can pass in a second argument to mapStateToProps(state, ownProps) which will give you access to the props passed into the component in mapStateToProps

    0 讨论(0)
  • 2021-01-30 05:28

    Using Decorators (@)

    If you are using decorators, the code below give an example in the case you want to use decorators for your redux connect.

    @connect(
        (state, ownProps) => {
            return {
                Foo: ownProps.Foo,
            }
        }
    )
    export default class Bar extends React.Component {
    

    If you now check this.props.Foo you will see the prop that was added from where the Bar component was used.

    <Bar Foo={'Baz'} />
    

    In this case this.props.Foo will be the string 'Baz'

    Hope this clarifies some things.

    0 讨论(0)
  • 2021-01-30 05:35

    mapStateToProps and mapDispatchToProps both take ownProps as the second argument.

    [mapStateToProps(state, [ownProps]): stateProps] (Function):
    [mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function):
    

    For reference

    0 讨论(0)
  • 2021-01-30 05:38

    There's a few gotchas when doing this with typescript, so here's an example.

    One gotcha was when you are only using dispatchToProps (and not mapping any state props), it's important to not omit the state param, (it can be named with an underscore prefix).

    Another gotcha was that the ownProps param had to be typed using an interface containing only the passed props - this can be achieved by splitting your props interface into two interfaces, e.g.

    interface MyComponentOwnProps {
      value: number;
    }
    
    interface MyComponentConnectedProps {
      someAction: (x: number) => void;
    }
    
    export class MyComponent extends React.Component<
      MyComponentOwnProps & MyComponentConnectedProps
    > {
    ....//  component logic
    }
    
    const mapStateToProps = (
      _state: AppState,
      ownProps: MyComponentOwnProps,
    ) => ({
      value: ownProps.value,
    });
    
    const mapDispatchToProps = {
      someAction,
    };
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
    

    The component can be declared by passing the single parameter:

    <MyComponent value={event} />
    
    0 讨论(0)
提交回复
热议问题