gpt4 book ai didi

javascript - PropTypes 位置的 Redux 最佳实践

转载 作者:行者123 更新时间:2023-12-01 03:01:21 25 4
gpt4 key购买 nike

想知道是否最好将 propType 定义放入包含所有 prop 逻辑的容器或实际使用 props 的演示者中。我可以看到两者的论据。

在容器中,您可以在一个地方跟踪所有 Prop 逻辑在演示者中确认它们将被正确使用。

感谢您的意见。

为了清晰起见进行更新

示例容器.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;

pros

all logic is in 1 location

2 different containers could work with a presenter

cons

presenter may need a type not known by just the container array for map

示例-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;

pros

propTypes written in 1 place for everything using the presenter

cons

not as flexable, propTypes could be seen as logic then logic is in both container and presenters

最佳答案

如果它是一个类组件,我喜欢在类创建后将 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;

因此,它非常清楚您应该通过 props 传递给组件的内容。这是您的组件的摘要。

关于javascript - PropTypes 位置的 Redux 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46412224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com