我怎样才能获得延迟渲染的路线?

时间:2018-03-26 09:40:47

标签: reactjs react-router

如何获得延迟渲染的路线?单击后,它将仅在2秒后呈现,而不是像react-router-dom中那样立即呈现。

感谢。

2 个答案:

答案 0 :(得分:1)

您可以在componentDidMount中运行set timeout以设置渲染状态。当渲染为false时,您在渲染函数中返回null,如果是,则渲染内容

class TestComp extends Component {

    constructor(){
        super()
        this.state = {
            render: false
        }
    }

    componentDidMount(){
        setTimeout(() => {
            this.setSTate({render: true})
        }, 2000)
    }



  render() {

    if(!this.state.render) return null

    return (
      <div>
        Page content
      </div>
    );
  }
}

至于你在第一次加载时只延迟渲染的问题,你可以尝试添加一个查询字符串来告诉组件是否需要延迟:

class TestComp extends Component {

  constructor(props){
    super(props)
    this.state = {
        render: this.props.location.delayLoad ? false : true
    }
  }

  componentDidMount(){

    if(!this.state.render){
      setTimeout(() => {
          this.setState({render: true}, () => {

            // in the callback, update your query string
            history.push({
              pathname: '/route',
              search: '?delayLoad=false'
            })

          })
      }, 2000)
    }

  }



  render() {

    if(!this.state.render) return null

    return (
      <div>
        Page content
      </div>
    );
  }
}

答案 1 :(得分:0)

严格回答你的问题: 如何获得延迟渲染的路线?

- &GT;我会在setTimeout的{​​{3}}属性中使用Route函数。

然后,回答你在评论中说明的附加条件(只有从链接访问的路径应该被延迟):

- &GT;我会按照@Stretch0的建议来使用参数。然后应在render的{​​{1}}函数中测试此参数。

相关问题