最佳答案
我还没有找到一个明确的答案,希望这不是重复。
我使用 React + Redux 作为一个简单的聊天应用程序。该应用程序由 InputBar、 MessageList 和 Container 组件组成。Container (正如您所想象的那样)包装了另外两个组件并连接到存储。我的消息以及当前消息(用户当前输入的消息)的状态保存在 Redux 存储中。简化结构:
class ContainerComponent extends Component {
...
render() {
return (
<div id="message-container">
<MessageList
messages={this.props.messages}
/>
<InputBar
currentMessage={this.props.currentMessage}
updateMessage={this.props.updateMessage}
onSubmit={this.props.addMessage}
/>
</div>
);
}
}
我遇到的问题发生在更新当前消息时。更新当前消息将触发一个更新存储的操作,该操作将更新通过容器并返回到 InputBar 组件的道具。
这是可行的,但是副作用是每次发生这种情况时,我的 MessageList 组件都会被重新呈现。MessageList 不接收当前消息,也没有任何理由更新。这是一个大问题,因为一旦 MessageList 变大,应用程序在每次更新当前消息时都会明显变慢。
我试过直接在 InputBar 组件中设置和更新当前消息状态(因此完全忽略了 Redux 体系结构) ,并“修复”了这个问题,但是如果可能的话,我想坚持使用 Redux 设计模式。
我的问题是:
如果更新了父组件,React 是否总是更新该组件中的所有直接子组件?
这里的正确方法是什么?