javascript - 状态改变后 React Component 不渲染
问题描述
您好,我在重新渲染下面的组件时遇到问题,您可以在第一个屏幕中看到我的代码,其中我有一个自定义组件:
class Ahelle extends React.Component{
constructor(props){
super(props)
this.state={
mamad:10
}
}
render(){
return (
<View style={{backgroundColor:"white"}}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true}/>
<TouchableOpacity style={{width:100,height:100,alignSelf:"center"}} onPress={()=>{this.setState({mamad:20})}}><Text>dddd</Text></TouchableOpacity>
</ScrollView>
</View>
);
}
}
这里我有一个自定义组件,我传递了一个默认值来显示,但是当我改变 state 时,它并没有改变我作为道具传递的值。这是我的自定义滑块组件及其状态、道具和任何其他详细信息。
class Test extends React.Component{
constructor(props){
console.log(props)
super(props)
this.state = {
value: props.defaultValue
};
}
render(){
return(
<Slider
style={{width: wp("70%")}}
value={this.state.value}
/>
)
}
}
export default Test;
查看实际问题 感谢您抽出宝贵时间
解决方案
您的滑块组件永远不会对传递的更新的道具值做任何事情。巧合的是,将传递的道具存储在本地组件状态中也是一种反应反模式。您可以而且应该直接食用它们。只需传递this.state.mamad
给value
道具并消费。您还可以通过将任何其他道具传播到滑块组件来传递它们。
class Test extends React.Component {
render() {
return (
<Slider
style={{ width: wp("70%") }}
value={this.props.value}
{...this.props}
/>
);
}
}
export default Test;
用法
<CustomSlider value={this.state.mamad} disabled={true} />
如果您真的想存储传递的defaultValue
道具并保持更新,请实现componentDidUpdate
生命周期功能。请注意,这不是推荐的解决方案。
class Test extends React.Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
value: props.defaultValue
};
}
componentDidUpdate(prevProps) {
const { defaultValue } = this.props;
if (prevProps.defaultValue !== defaultValue) {
this.setState({ value: defaultValue});
}
}
render() {
return <Slider style={{ width: wp("70%") }} value={this.state.value} />;
}
}
export default Test;
推荐阅读
- java - 在java中导入相同命名的包
- javascript - 如何将值从 Node 发送到 HTML 以在 JavaScript 中处理?
- javascript - 水平滚动事件未在 Windows 上触发
- python - 单位置索引器在 while 循环 pandas 上越界
- css - 导入散列 CSS className 并在另一个文件中选择它
- python - Flask-sqlalchemy 'Models_committed' 没有调用通过装饰器注册的函数
- c - 如何正确归一化 q15 定点中的 pid 系数
- azure - 将 Xamarin 和 Azure B2C 与 MSAL 结合使用
- python - 如何从输出中删除索引
- angular - Ionic 4 离子选择选项值变化