簡體   English   中英

關於PropTypes位置的Redux最佳做法

[英]Redux best practices for PropTypes location

我想知道是否最好將propType定義放到具有所有prop邏輯的容器中或將實際使用prop的presenter中。 我可以看到兩個參數。

在容器中,您可以將所有道具邏輯都集中在一處,而在演示者中,確認它們將被正確使用。

感謝您的輸入。

為清楚起見進行更新

example-container.js

import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import ButtonPresenter from './some/file';

const mapStateToProps = (store, props) => {
  return ({
    example: Number(5),
  });
};

const mapDispatchToProps = (dispatch, props) => ({
  onClick: id => { console.log(id) },
});

ButtonPresenter.propTypes = {
  onClick: PropTypes.func.isRequired,
  example: PropTypes.number.isRequired,
}

const ButtonContainer = connect(mapStateToProps, mapDispatchToProps)(BoxPresenter);

export default ButtonContainer;

優點

所有邏輯都在1個位置

主持人可以使用2個不同的容器

缺點

演示者可能需要一種僅由容器數組未知的類型

example-presenter.js

import React from 'react';
import PropTypes from 'prop-types';

const ButtonPresenter = ({example, onClick}) => {
  return (
    <button onClick={onClick}>{example}</button>
  );
};

ButtonPresenter.propTypes = {
  onClick: PropTypes.func.isRequired,
  example: PropTypes.number.isRequired,
}

export default ButtonPresenter;

優點

使用主持人在所有地方在1個地方編寫的propTypes

缺點

不那么靈活,propTypes可以看作是邏輯,然后邏輯既在容器中又在演示者中

如果它是一個Class Component ,我想在創建類之后將propTypes和defaultProps放在最頂部:

import React from 'react';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
    static propTypes = {
        prop1: PropTypes.string.isRequired,
        prop2: PropTypes.bool,
        prop3: PropTypes.func
    };

    defaultProps = {
        prop2: false,
        prop3: () => {}
    };

    constructor() {}
    render() {}
}

export default MyComponent;

或對於功能組件 ,我喜歡創建變量並將其保留在導入之后:

import React from 'react';
import PropTypes from 'prop-types';

const propTypes = {
    prop1: PropTypes.string.isRequired,
    prop2: PropTypes.bool,
    prop3: PropTypes.func
};

const defaultProps = {
    prop2: false,
    prop3: () => {}
};

const MyComponent = props => {

}

MyComponent.propTypes = propTypes;
MyComponent.defaultProps = defaultProps;

export default MyComponent;

這樣就很清楚您應該通過prop傳遞給組件什么。 這是您組件的摘要。

在您的問題上,我看不到Redux和PropTypes之間的關系。

無論如何,我會在可能被重用/消耗的任何React組件上指定PropTypes 對我而言,對商店綁定的最高組件執行此操作沒有任何意義

雖然這可能是基於意見的

[編輯:]
我可能會丟失一些東西,但是afaik只能將根組件(層次結構中較高的組件)綁定到商店。 因此,我看不到您將如何在其他任何地方使用它並將屬性傳遞給它。 總而言之,只有第二個片段對我有意義,該組件的API自包含在文件中,使合同清晰明了。 eiffel.com/values/design-by-contract

暫無
暫無

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

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