簡體   English   中英

ComponentDidMount 與 useEffect

[英]ComponentDidMount vs useEffect

有一個 class 組件工件。 我想把它轉換成function組件,用同樣的方法實現,但是有問題。

與class類型不同的是,function類型在圖片移動后不停留,返回到創建的地方。

這是 function 組件。

const [dogs, setDogs] = useState([])

function addDog(){
    // setDogs([...dogs, {id: dogCount++}])
    dogCount++;
    console.log(dogCount)
    // console.log(dogs)
    const newDog = {id: dogCount, bottom: 125}
    setDogs([...dogs, newDog])
  }
  
 return (
    <View style={styles.entirebottomsheet}>
      <View style={styles.container}>
        <TouchableOpacity onPress={()=>{addDog();}} style={styles.dogButton}>
          <Text>Dog</Text>
        </TouchableOpacity>
         {dogs.map(dog => {
           return ( 
            <DogContainer
              key={dog.id}
              style={{bottom: dog.bottom, position: 'absolute'}}
            />
          ); 
         })}
      </View>
    </View>
  );
  
  
  function DogContainer () {
  const positionX = new Animated.Value(0);
  const positionY = new Animated.Value(0);
  
  // DogContainer.defaultProps = {
  //   onComplete() {}
  // }

  const getDogStyle = () => ({
    transform: [{translateX: positionX}],
  });

  useEffect(() => {
    Animated.spring(positionX, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start();
    Animated.spring(positionY, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start();
    return (
      console.log('finish')
    )
  }, []);


  return (
    <Animated.View style={[{ bottom: 125},{
      transform: [{translateX: positionX}, {translateY: positionY}],
    }]}>
      <Image source={dogImg} style={{width: 60, height: 60}}/>
    </Animated.View>
  );
}

這是 class 組件。

export default class App extends React.Component {
  // let {up} = this.props.up;

  state = {
    dogs: [],
    cats: [],
    chicks: [],
  };

  addDog = () => {
    console.log(...this.state.dogs);
    this.setState(
      {
        dogs: [
          ...this.state.dogs,
          {
            id: dogCount,
            bottom: 125,
          },
        ],
      },
      () => {
        dogCount++;
      },
    );
  };

  removeDog = id => {
    this.setState({
      dogs: this.state.dogs.filter(dog => {
        return dog.id !== id;
      }),
    });
  };

  addCat = () => {
    console.log(...this.state.cats);
    this.setState(
      {
        cats: [
          ...this.state.cats,
          {
            id: catCount,
            bottom: 125,
          },
        ],
      },
      () => {
        catCount++;
      },
    );
  };

  removeCat = id => {
    this.setState({
      cats: this.state.cats.filter(cat => {
        return cat.id !== id;
      }),
    });
  };

  addChick = () => {
    console.log(...this.state.chicks);
    this.setState(
      {
        chicks: [
          ...this.state.chicks,
          {
            id: chickCount,
            bottom: 125,
          },
        ],
      },
      () => {
        chickCount++;
      },
    );
  };

  removeChick = id => {
    this.setState({
      chicks: this.state.chicks.filter(chick => {
        return chick.id !== id;
      }),
    });
  };

  render() {
    return (
      <GestureHandlerRootView>
      <View style={styles.entirebottomsheet}>
        <View style={styles.container}>
            <TouchableOpacity onPress={this.addDog} style={styles.dogButton}>
              <Text>Dog</Text>
            </TouchableOpacity>
          {this.state.dogs.map(dog => {
            return (
              <DogContainer
                key={dog.id}
                style={{bottom: dog.bottom, position: 'absolute'}}
                onComplete={() => this.removeDog(dog.id)}
              />
            );
          })}
        </View>

        <View style={styles.container}>
          <TouchableOpacity onPress={this.addCat} style={styles.catButton}>
            <Text>Cat</Text>
          </TouchableOpacity>
          {this.state.cats.map(cat => {
            return (
              <CatContainer
                key={cat.id}
                style={{bottom: cat.bottom, position: 'absolute'}}
                onComplete={() => this.removeCat(cat.id)}
              />
            );
          })}
        </View>

        <View style={styles.container}>
          <TouchableOpacity onPress={this.addChick} style={styles.chickButton}>
            <Text style={{position: 'absolute'}}>Chick</Text>
          </TouchableOpacity>
          {this.state.chicks.map(chick => {
            return (
              <ChickContainer
                key={chick.id}
                style={{bottom: chick.bottom, position: 'absolute'}}
                onComplete={() => this.removeChick(chick.id)}
              />
            );
          })}
        </View>
      </View>
      </GestureHandlerRootView>
    );
  }
}

class DogContainer extends React.Component {
  state = {
    position: new Animated.ValueXY({
      x: 0,
      y: 0,
    }),
  };

  static defaultProps = {
    onComplete() {},
  };

  componentDidMount() {
    Animated.spring(this.state.position.x, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(this.props.onComplete);

    Animated.spring(this.state.position.y, {
      duration: 1000,
      toValue: -340,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(this.props.onComplete);
  }

  getDogStyle() {
    return {
      transform: [
        {translateY: this.state.position.y},
        {translateX: this.state.position.x},
      ],
    };
  }

  render() {
    return (
      <Animated.View style={[this.getDogStyle(), this.props.style]}>
        <Image source={dogImg} style={{width: 60, height: 60, borderRadius: 30}} />
      </Animated.View>
    );
  }
}

嘗試使用useRef()鈎子

    function DogContainer () {
          const positionX = useRef(new Animated.Value(0)).current;
          const positionY = useRef(new Animated.Value(0)).current;
...

在基於類的 DogContainer 版本中, DogContainer坐標是 state 的一部分。

class DogContainer extends React.Component {
  state = {
    position: new Animated.ValueXY({
      x: 0,
      y: 0,
    }),
  };

  static defaultProps = {
    onComplete() {},
  };

  componentDidMount() {
    Animated.spring(this.state.position.x, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(this.props.onComplete);

    Animated.spring(this.state.position.y, {
      duration: 1000,
      toValue: -340,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(this.props.onComplete);
  }

  getDogStyle() {
    return {
      transform: [
        {translateY: this.state.position.y},
        {translateX: this.state.position.x},
      ],
    };
  }

  render() {
    return (
      <Animated.View style={[this.getDogStyle(), this.props.style]}>
        <Image source={dogImg} style={{width: 60, height: 60, borderRadius: 30}} />
      </Animated.View>
    );
  }
}

Function 組件使用useState鈎子

function DogContainer ({ onComplete = () => {} }) {
  const [position, setPosition] = React.useState(
    new Animated.ValueXY({
      x: 0,
      y: 0,
    })
  );

  const getDogStyle = () => ({
    transform: [{
      translateX: position.x,
      translateY: position.y,
    }],
  });

  useEffect(() => {
    Animated.spring(position.x, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(onComplete);
    Animated.spring(position.y, {
      duration: 1000,
      toValue: width / 3,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(onComplete);

    console.log('finish');
  }, []);

  return (
    <Animated.View
      style={[
        { bottom: 125},
        { transform: [
            { translateX: position.x },
            { translateY: position.y }
          ],
        }
      ]}
    >
      <Image source={dogImg} style={{ width: 60, height: 60 }} />
    </Animated.View>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM