如何从componentDidUpdate()中获取值并将其保存,以便以后可以使用它进行显示

时间:2019-01-10 18:49:28

标签: javascript reactjs

export default class newroom extends Component {

  constructor(props) {
    super(props)
    this.state = {
       currentUser:NaN,
       rooms:NaN
    }

  }

  static getDerivedStateFromProps(nextProps, prevState){
    // console.log(prevState)
    const {currentUser}  = nextProps
    return {currentUser}
  }


  componentDidUpdate(){
    const {...currentUser} = this.state.currentUser
    currentUser.getJoinableRooms()
            .then((rooms)=>{
              //this rooms has a id and a name which i want to store so that i can display in the h3 tag
            })
            .catch(err=>console.log(err))

  }

  render() {

    return (
      <div className="new-room">
        <h3>{}</h3>
      </div>
    )
  }
}

getDerivedStateFromProps()方法返回currentUser对象并设置状态, 并且当curentUser更新update时会触发componentDidUpdate方法并获取rooms对象,但我无法弄清楚如何存储rooms.id和rooms.name以便以后可以在h3标签中显示。 componentDidUpdate()每次都会更新状态,并再次触发该方法。

2 个答案:

答案 0 :(得分:0)

您应该避免使用getDerivedStateFromProps,并在componentDidMount方法(首次安装时)中进行抓取:

export default class newroom extends Component {

  constructor(props) {
    super(props)
    this.state = {
       rooms:NaN
    }
  }

  componentDidMount(){
    const { currentUser } = this.props

    currentUser.getJoinableRooms()
            .then((rooms)=>{
              this.setState({rooms})
            })
            .catch(err=>console.log(err))

  }

  render() {

    return (
      <div className="new-room">
        {rooms.map(room => <h3 key={room.id}>{room.id}</h3>)}
      </div>
    )
  }

答案 1 :(得分:0)

在调用getJoinableRooms之前将当前道具与以前的道具进行比较

componentDidUpdate(prevProps, prevState){
    if(prevProps.currentUser.id !== this.props.currentUser.id){
         this.props.currentUser.getJoinableRooms()
            .then((rooms)=>{
                //set state here
         })
        .catch(err=>console.log(err))

     }


}