使用带反应的redux时使用defaultProps会发生什么?

时间:2018-02-02 01:09:39

标签: reactjs redux react-redux state

在使用redux中的mapStateToProps时,发现使用defaultProps有什么影响?

举个例子:

class BasicComp extends React.Component{

    render() {
        return (<div>{this.props.content}</div>);
    }

}


BasicComp.defaultProps = {
    content: "some_text",
}


const mapStateToProps = (store, ownProps) => {

    return {
        content: ownProps.content || "some_other_text",
    }
}


const BasicCompRDX = connect(
    mapStateToProps
)(BasicComp)

我可以对此进行测试并找到输出,但更倾向于专家意见关于redux如何在哲学层面处理这个问题。

2 个答案:

答案 0 :(得分:2)

让我们从 defaultProps 的定义开始:

  

defaultProps可以定义为组件类本身的属性,以设置类的默认道具。这用于未定义的道具,但不用于空道具。

然后简化BasicCompRDX的样子:

class BasicCompRDX extends React.Component {
  // some react context - injection of redux store (dispatch, getState) API

  // some lifecycle hooks with `shouldComponentUpdate` implemented to optimize perf

  return() {
    const ownProps = this.props
    const stateProps = mapStateToProps(store.state, ownProps)
    const dispatchProps = mapDispatchToProps(store.dispatch, ownProps) || store.dispatch

    return <BasicComp {...stateProps, ...dispatchProps, ...ownProps} />
  }
}

由于mapStateToProps函数返回

  

{content:ownProps.content || “some_other_text”}

它将作为<BasicComp content={ownProps.content || 'some_other_text"} content={ownProps.content} {...otherProps} />传递给BasicComp,所以显然BasicComp的内容支持定义为'some_other_text'的后备,因此defaultProps根本不会被使用。

免责声明:不是redux专家。

答案 1 :(得分:0)

以下是测试结果,似乎在使用connect时会忽略defaultProps。非常喜欢redux专家的见解!?

试验:

describe('BasicComp', () => {


    test('BasicComp init', () => {

        const component = render(
            <Provider store={store}>
                <BasicCompRDX />
            </Provider>
        );
        expect(renderToJson(component)).toMatchSnapshot();
    });


    test('BasicComp init with prop', () => {

        const component = render(
            <Provider store={store}>
                <BasicCompRDX content={"new content!!"}/>
            </Provider>
        );
        expect(renderToJson(component)).toMatchSnapshot();
    });


    test('BasicComp init no RDX', () => {

        const component = render(
            <BasicComp />
        );
        expect(renderToJson(component)).toMatchSnapshot();
    });


    test('BasicComp init no RDX with prop', () => {

        const component = render(
            <BasicComp content={"testing is useful!!"}/>
        );
        expect(renderToJson(component)).toMatchSnapshot();
    });

});

测试输出:

// Jest Snapshot v1

出口[BasicComp BasicComp init 1] =`

  some_other_text

`;

出口[BasicComp BasicComp init no RDX 1] =`

  SOME_TEXT

`;

出口[BasicComp BasicComp init no RDX with prop 1] =`

  测试很有用!!

`;

出口[BasicComp BasicComp init with prop 1] =`

  新内容!!

`;

相关问题