Does this.setState return promise in react

后端 未结 6 1195
陌清茗
陌清茗 2020-12-03 07:19

I made my componentWillMount() async. Now I can using await with the setState.

Here is the sample code:

compon         


        
6条回答
  •  时光说笑
    2020-12-03 08:12

    You can simple customize a Promise for setState

      componentWillMount = async () => {
        console.log(1);
        await this.setRooms();
        console.log(3);
      };
    
      setRooms = () => {
        const { fetchRooms } = this.props;
        return fetchRooms().then(({ room }) => {
          this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, _ =>
            console.log(2)
          );
        });
      };
    

    Or

      setRooms = async () => {
        const { fetchRooms } = this.props;
        const { room } = await fetchRooms();
    
        return new Promise(resolve => {
          this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, _ =>
            resolve()
          );
        });
      };
    

    Hope this help =D

提交回复
热议问题