ReactJs:如何在渲染组件时传递初始状态? [英] ReactJs: How to pass the initial state while rendering a component?
问题描述
我知道在渲染组件时我可以传递 props
。我也知道 getInitialState
方法。但问题是, getInitialState
并不是很有帮助,因为我的组件不知道它的初始状态。我做。所以我想在渲染时传递它。
I know I can pass props
while rendering a component. I'm also aware of the getInitialState
method. But the problem is, getInitialState
isn't quite helping because my component doesn't know it's initial state. I do. So I want to pass it while I'm rendering it.
像这样的东西(伪代码):
Something like this (pseudo-code):
React.render(<Component initialState={...} />);
我知道我可以使用 prop
来作为初始状态工作,但这有点像反模式。
I know I could use a prop
to work as the initial state but this smells like an anti-pattern.
我该怎么办?
编辑清晰度
想象一下,我有一个 CommentList
组件。到我第一次渲染它时,初始状态对应于我数据库中当前注释的快照。由于用户包含评论,此列表将更改,这就是为什么它应该是州
而不是道具
。现在,为了呈现注释的初始快照,我应该将它传递给 CommentsList
组件,因为它无法知道它。我的困惑是,我看到传递此信息的唯一方法是通过道具
这似乎是反模式。
Imagine I have a CommentList
component. By the time I first render it, the initial state corresponds to the snapshot of current comments from my database. As the user includes comments, this list will change, and that's why it should be a state
and not props
. Now, in order to render the initial snapshot of comments I should pass it to the CommentsList
component, because it has no way to know it. My confusion is that the only way I see to pass this information is through a props
which seems to be an anti-pattern.
推荐答案
只有永久性组件才能在 getInitialState
中使用道具。如果同步是您的目标,则 getInitialState
中的道具是反模式。 getInitialState
仅在首次创建组件时调用,因此可能会引发一些错误,因为事实来源并不是唯一的。 查看此答案。
Only permanent components might be able to use props in the getInitialState
. Props in getInitialState
is an anti-pattern if synchronization is your goal. getInitialState
is only called when the component is first created so it may raise some bugs because the source of truth is not unique. Check this answer.
使用从父级向下传递的props,在
中生成状态getInitialState经常导致重复真实来源,即真实数据所在的
。在可能的情况下,动态计算值
以确保它们以后不会失去同步并导致
维护问题
Using props, passed down from parent, to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble
你仍然可以这样做:
getInitialState: function() {
return {foo: this.props.foo}
}
因为它们将是你的默认道具应用程序。但是只要你使用prop设置一个可能不会改变的值,你就可以在 render
函数中使用相同的prop。
As they will be the default props for your app. But as long as you are using a prop to set a value that presumably won't change, you can use the same prop inside of the render
function.
<span>{this.props.foo}</span>
这个道具不会被修改,所以每次使用它都没有问题 render
被调用。
This props won't be modified, so no problem using it each time the render
is called.
编辑答案:
在这种情况下,您的初始状态不应该是道具,应该是ajax调用填充评论列表。
In this case your initial state should not be a prop, should be an ajax call which populates the comment list.
这篇关于ReactJs:如何在渲染组件时传递初始状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!