首页 > 解决方案 > 状态改变后 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;

查看实际问题 感谢您抽出宝贵时间

标签: javascriptreactjsreact-nativestate

解决方案


您的滑块组件永远不会对传递的更新的道具值做任何事情。巧合的是,将传递的道具存储在本地组件状态中也是一种反应反模式。您可以而且应该直接食用它们。只需传递this.state.mamadvalue道具并消费。您还可以通过将任何其他道具传播到滑块组件来传递它们。

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;

推荐阅读