当props通过parent状态更新时,React - child不更新
react - child not updating when props updated through parent state
我有一个react native组件-
export default class Chat extends Component {
constructor(props) {
super(props);
this.state = {
behavior: 'padding',
text: '',
messages: this.props.chat.messages
};
}
updateText() {
this.setState({
messages: this.state.messages.concat( { message: this.state.text } )
})
}
render() {
return (
<KeyboardAvoidingView behavior={this.state.behavior} style={styles.container}>
<View style={styles.chatContainer}>
<MessageList messages={this.state.messages} />
</View>
<View style={styles.textContainer}>
<BorderedTextInput
placeholder="Type something..."
onSubmitEditing={ this.updateText.bind(this) }
onChangeText={(text) => this.setState({text})}
value={this.state.text}
style={styles.textInput} />
<IconBar />
</View>
</KeyboardAvoidingView>
);
}
}
在它的状态中有消息数组,当使用文本输入时更新。这将传递给MessageList组件。
export default class MessageList extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(this.props.messages),
};
}
_renderRow(chat){
return (
<FadeInListRow>
<View style={this._bubbleContainerStyle(chat)}>
<Text style={this._bubbleStyles(chat)}>{chat.message}</Text>
</View>
</FadeInListRow>
)
}
render() {
return (
<View style={styles.container}>
<View style={styles.timeContainer}>
<Text style={styles.timeText}>
Mon, Jun 2, 22:09
</Text>
</View>
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
contentContainerStyle={styles.listView}
style={{flex: 1, paddingTop: 50}}
/>
</View>
)
}
}
我期望_renderRow再次被调用,我的列表视图更新时,父状态更新。事实并非如此。知道我哪里做错了吗?
当前代码看起来不错。我想建议两件事:
-
确认
state
中的message
属性确实更新为onSubmit()
。您可以在chat
类的return
命令之前记录它 -
确认
MessageList
组件的props
中的message
属性在父组件更新的相同周期内获得更新
我这么说有一个前提:大多数状态更新的问题通常是因为与数据更新不一致。如果数据没有改变,组件就不会被重新呈现。
相关文章:
- React js更改状态不会更新组件
- React-状态未更新
- React应用程序:道具在下一个事件后更新
- 如何让React JS点击处理程序在执行时更新DOM
- React:用父级状态更改更新子级
- 在for循环中未正确更新React本机密钥
- 正在服务器上呈现或更新react元素
- ReactJS:如何从 DOM 更新 React
- 在Day Change上更新React[Native]视图
- 使用继电器更新React状态
- 从iOS UIWebView更新React组件中元素的值
- 更新React组件共享状态
- 更新React中两个组件之间的数据
- 使用不变性助手更新React状态下的数组对象
- 我可以更新React.js中的组件's props吗?
- 按键更新React组件
- 更新react redux中的深层嵌套状态(规范化)
- 使用postal.js更新react组件
- 使用新数据更新React组件
- 如何更新 React 本地存储