【问题标题】:How to re-render component instead of calling constructor?如何重新渲染组件而不是调用构造函数?
【发布时间】:2019-05-07 17:12:51
【问题描述】:

我有一个带有进度条的项目的 FlatList,我想更改一个项目的进度。对于进度条,我制作了一个自定义组件。但是每次我更改一个项目的进度时,他都会重新渲染项目,但组件不会重新渲染,而是调用构造函数。由于进度动画,这是有问题的。

我尝试添加诸如 componentWillReceiveProps 和 componentWillUpdate 之类的函数,但没有被调用。

物品:

<View style={styles.node}>
  <PercentageBar value={item.progress} />
</View>

组件:

  constructor(props) {
    super(props);
    this.state = {
      animHeight: new Animated.Value(this.props.value),
    };
  }

  componentDidMount() {
    Animated.timing(this.state.animHeight,
      {
        toValue: this.props.value,
        duration: 200,
      }
    ).start();
  }

<View style={styles.background}>
  <Animated.View style={{height: this.state.animHeight.interpolate({
            inputRange: [0, 1],
            outputRange: ['0%', '100%'],
          }}></Animated.View>
</View>

我希望它使用新的道具重新渲染,而不是调用构造函数并重置组件。

【问题讨论】:

  • 你是否使用了键,以便 React 知道它仍然是同一个项目?你能创建一个minimal reproducible example吗?
  • 哦,谢谢,索引上的 keyExtractor 就足够了。它现在可以与 item-name 上的键一起使用,但这不是唯一的。我现在应该生成随机密钥吗?

标签: javascript react-native


【解决方案1】:

通过插入如下所示的条件语句来更改要运行的代码。

example.js

componentDidUpdate(){
   if(true){
   ...
  }
}

或

每次更改代码时都可以重新渲染。

example.js

render{
//your code
return();
}

程序运行顺序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2020-01-16
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多