我有上级组件,其中也包括下级组件。我将一些道具从父母那里传递给孩子。我的问题是当我更改滑块以在父组件上获得新值时,重新渲染在父组件上不起作用。这也导致无法重新渲染子组件。
在更改滑块时,函数将被执行并且状态将被更改为新值。但是此setstate不会触发重新呈现。我正在调试以下代码,控制台日志是这样的(将滑块从0更改为1);
delay -> 0
delay timetypes -> 0 (6 times executed)
delay -> 1
当我触摸其中一种可触摸的不透明度时,得到this.state.delay = 0 但是我通过滑块将0更改为1。
// welcome.js
export default class welcome extends Component {
constructor(props) {
super(props);
this.state = {
GridViewItems: [
{ key: "1 min game", min: 1, sec: 0 },
{ key: "3 min game", min: 3, sec: 0 },
{ key: "5 min game", min: 5, sec: 0 },
{ key: "7 min game", min: 7, sec: 0 },
{ key: "10 min game", min: 10, sec: 0 },
{ key: "15 min game", min: 15, sec: 0 }
],
value : 0
};
}
GetGridViewItem(item) {
Alert.alert(item);
}
change(value) {
console.log("change value -> " + value );
this.setState({
value: value
})}
render() {
console.log("delay -> " + this.state.value);
return (
<View style={styles.MainContainer}>
<Text style={styles.welcomeText}>Welcome ChessClock</Text>
<Text style={styles.text}>Delay Time: {this.state.value}</Text>
<Slider
style = {styles.slider}
step={1}
maximumValue={20}
value={this.state.value}
onValueChange={(val)=> this.setState({value: val})}
/>
<FlatList
data={this.state.GridViewItems}
renderItem={({ item }) => (
<TimerTypes
navigation={this.props.navigation}
BlockStyle={styles.GridViewBlockStyle}
TextStyle={styles.GridViewInsideTextItemStyle}
title={item.key}
time={item.min * 60 + item.sec}
delay = {this.state.value}
/>
)}
numColumns={2}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: "center",
flex: 1,
margin: 10,
paddingTop: Platform.OS === "ios" ? 20 : 0
},
GridViewBlockStyle: {
justifyContent: "center",
flex: 1,
alignItems: "center",
height: 100,
margin: 5,
backgroundColor: "#05BC87"
},
GridViewInsideTextItemStyle: {
color: "#fff",
padding: 10,
fontSize: 18,
justifyContent: "center"
},
welcomeText: {
color: "#0F2284",
padding: 60,
fontSize: 30,
justifyContent: "center",
textAlign: "center"
},
text: {
fontSize: 20,
justifyContent: "center",
marginLeft:10
},
slider: {
width: '100%',
marginBottom: 25,
justifyContent: "center",
alignItems : "center"
}
});
// timeTypes
export default class timeTypes extends Component {
constructor(props) {
super(props);
this.state = {
delay : props.delay
}
}
componentWillReceiveProps(nextProps) {
this.setState({ delay: nextProps.delay });
}
render() {
console.log("delay timetypes -> " + this.props.delay);
console.log("delay timetypes -> " + this.state.delay);
return (
<TouchableOpacity onPress={() => this.props.navigation.navigate('Home', {
time: this.props.time,
delay : this.state.delay
})}
style={this.props.BlockStyle} >
<Text style={this.props.TextStyle}>
{this.props.title}
</Text>
</TouchableOpacity >
);
}
}
快乐的路径应该是在更改滑块以获取新数字时,父级将重新呈现,子级应获取新值。
答案 0 :(得分:1)
根据文档:
FlatList是一个PureComponent,这意味着它不会在以下情况下重新渲染 道具保持相等。确保所有内容都为renderItem 函数所依赖的是作为不传递的prop(例如extraData) ===更新后,否则您的UI可能不会更新。这包括数据属性和父组件状态。
因此,请尝试将extraData={ this.state.value }
添加到FlatList组件中