例如:
<Counter start="10">
...
export default class Counter extends React.Component {
constructor(props) {
super();
this.state = {
start: props.start
};
}
}
我搜索了这个问题,我得知我发现的答案已经过时了
关于StackOVerflow的问题
-
ReactJS: Why is passing the component initial state a prop an anti-pattern?
-
ReactJs: How to pass the initial state while rendering a component?
但我在React博客中发现了这篇文章:React v0.13.0 Beta 1
在那篇文章中,作者正是我想要的,正如我所理解的那样 getDefaultProps
现已弃用 .
所以问题是:通过道具传递状态仍然是反模式?
1 回答
恕我直言'是',因为你给人的印象是改变道具 Value 会改变不会发生的组件的行为 . 当我更改开始参数时,您的组件的行为将完全相同 .
印象很酷,但需求是真实的 . 有时当我需要这种行为时,我只需将我的道具命名为
initialFoo
或defaultBar
.