Skip to main content

状态

有两种类型的数据控制组件:propsstateprops 由父组件设置,并且在组件的整个生命周期中都是固定的。对于要改变的数据,我们必须使用 state

¥There are two types of data that control a component: props and state. props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.

一般来说,你应该在构造函数中初始化 state,然后当你想改变它时调用 setState

¥In general, you should initialize state in the constructor, and then call setState when you want to change it.

例如,假设我们想要制作一直闪烁的文本。创建闪烁组件时,文本本身会设置一次,因此文本本身是 prop。"文本当前是打开还是关闭" 随着时间的推移而变化,因此应保留在 state 中。

¥For example, let's say we want to make text that blinks all the time. The text itself gets set once when the blinking component gets created, so the text itself is a prop. The "whether the text is currently on or off" changes over time, so that should be kept in state.

在实际应用中,你可能不会使用计时器设置状态。当你从服务器或用户输入获得新数据时,你可以设置状态。你还可以使用 ReduxMobX 等状态容器来控制数据流。在这种情况下,你将使用 Redux 或 MobX 来修改你的状态,而不是直接调用 setState

¥In a real application, you probably won't be setting state with a timer. You might set state when you have new data from the server, or from user input. You can also use a state container like Redux or MobX to control your data flow. In that case you would use Redux or MobX to modify your state rather than calling setState directly.

当调用 setState 时,BlinkApp 将重新渲染其组件。通过在计时器内调用 setState,组件将在每次计时器计时时重新渲染。

¥When setState is called, BlinkApp will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.

State 的工作方式与 React 中的工作方式相同,因此有关处理状态的更多详细信息,你可以查看 React.Component API。此时,你可能已经注意到我们的大多数示例都使用默认文本颜色。要自定义文本颜色,你必须 了解样式

¥State works the same way as it does in React, so for more details on handling state, you can look at the React.Component API. At this point, you may have noticed that most of our examples use the default text color. To customize the text color, you will have to learn about Style.