React Native - 组件回调第一次为视图设置动画,但在后续调用中没有

React Native - component callback animates a view first time but not on subsequent calls

我有一个动画,它是通过发送到 render() 中的组件的回调函数触发的。动画只是一些文本从屏幕右边缘外移过屏幕并离开左侧。第一次触发回调时它完美运行,但在后续回调中什么也看不到,也没有错误。相关代码如下:

     import { Animated, Easing....} from 'react-native';
        
        class Play extends Component {
          constructor() {
            super();
            this.state = {currSectName:"Intro",  
            sectNameXcord: new Animated.Value(Dimensions.get('window').width),....}
          }
    
         sectNameTraverse = (newSect) =>{
            this.state.currSectName = newSect;
            this.state.sectNameXcord = new Animated.Value(Dimensions.get('window').width);
    
            //run the animation
            Animated.timing(
              this.state.sectNameXcord,
              {
                toValue: -320,
                duration: 3000, // the duration of the animation
                easing: Easing.linear, // the style of animation 
                useNativeDriver: true
              }
            ).start((res)=>{
                console.log(res);
            }); 
          } 
    
          render() {
               return (
                 <>
                  <Animated.View style={{position: 'absolute',top:100,
transform: [{translateX: this.state.sectNameXcord }]}}>
                    <Text style={{ color:"white",opacity:0.5,fontStyle: 'italic',fontWeight: 'bold',fontSize:99}}>
                     {this.state.currSectName}
                    </Text>
                  </Animated.View>
    
                 <Player
                 sectionChange={(newSect) => {this.sectNameTraverse(newSect)}}
                 />
          }

在后续回调中,以下为真:

我猜这可能与 instances/binding 有关,但我还不够好 用 React Native 来修复它。坚持了 2 天,真的需要一些帮助。

非常感谢。

你不应该改变状态。您应该使用“setState”来更新状态。

  sectNameTraverse = (newSect) => {
    this.setState(
      { 
        currSectName:newSect,
        sectNameXcord: new Animated.Value(Dimensions.get('window').width)
        },
      () => {
        //run the animation
        Animated.timing(this.state.sectNameXcord, {
          toValue: -320,
          duration: 3000, // the duration of the animation
          easing: Easing.linear, // the style of animation
          useNativeDriver: true,
        }).start((res) => {
          console.log(res);
        });
      }
    );
  };

这是我创建的 snack