在componentDidMount中触发重新渲染

时间:2018-12-04 07:11:22

标签: reactjs redux

在组件的生命周期中,如果重新渲染是由componentDidMount()中的某些同步操作触发的,则用户是否有机会在浏览器上看到第一个渲染内容? 例如如果我通过redux切换了componentDidMount()中的开始下载布尔值标志,则将导致重新渲染,因为该标志已映射到该组件的redux。

-------更新信息-----

同步操作只是将开始下载标志更改为true,并且该标志映射到组件,在该组件中检查该标志以确定render()中的JSX内容。在redux中,在将标志设置为true之后,立即开始下载操作。下载完成后,redux会将标志设置为false。 考虑以下生命周期顺序:

render() //JSX A  
componentDidMount() // the flag is set  
render() // re-render JSX B  

无论浏览速度有多快,JSX A都会显示在浏览器中吗?
在componentDidMount()中调用的动作创建者:

export const downloadArticleList = () => {
        return (dispatch, getState) => {
        // set start flag to true synchronously, before axios.get
            dispatch(listDownloadStart());  
            axios.get('/articles')
                .then(response => {
                //set the flag to false and update the data
                    dispatch(saveArticleList(response.data))
                })
                .catch(err => {
                    dispatch(serverFail(err))
                    console.log("[downloadArticleList]] axios", err);
                })
        }
    }

这是SPA,没有SSR。

3 个答案:

答案 0 :(得分:1)

这取决于几件事:

  • 同步操作需要多长时间
  • 您正在执行SSR(因此会有一些时间专门用于DOM补液)

通常,我会将其视为反模式

答案 1 :(得分:1)

我们在评论中讨论的是示例:

interface ExampleComponentProps {

}
interface ExampleComponentState {
    loading: boolean;
}

export class ExampleComponent extends React.Component<ExampleComponentProps, ExampleComponentState>{
    constructor(props, context) {
        super(props, context);

        this.state = { loading: true };
    }

    componentDidMount() {
        //some method {}

        //after get result 
        this.setState({
            loading: false
        })
    }

    render() {
        return (
            <div>
                <Spin spinning={this.state.loading} >
                    //Your COmponent here
                </Spin>
            </div>
        )
    }
}

答案 2 :(得分:0)

如果您的项目很复杂,最简单的方法是使用

repeat = 1000000;
start = Date.now();

for (var i = repeat; i >= 0; i--) {
	var string = 'Error: android.java.lang.NullPointerException.checked';
	var regex = /(.*)\.([A-Za-z]+Exception)(.*)/g;
	var match = string.replace(regex, "$2");
}

end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");
相关问题