首页 > 解决方案 > 在渲染函数之后写变量和在构造函数中写“变量的this.name”有什么区别?

问题描述

像这样在渲染函数之后编写变量有什么区别:

render() {
var headers=[
    { key: 'userId', label: 'User ID' },
    { key: 'id', label: 'ID' },
    { key: 'title', label: 'Title' },
    { key: 'body', label: 'Body' }
];
    return (

并在构造函数中写入“this.name of variable”,如下所示:

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            users: []
        };

        this.headers = [
            { key: 'userId', label: 'User ID' },
            { key: 'id', label: 'ID' },
            { key: 'title', label: 'Title' },
            { key: 'body', label: 'Body' }
        ];

    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            return response.json();
        }).then(result => {
            this.setState({
                users:result
            });
        });
    }

    render() {

除了当我在第一个中调用它时我写 { headers } 而在第二个中我写 {this.headers}

注意:这里不是var vs this,是create-react-app中主app类的结构及其与前面代码写入位置的关系。

标签: javascriptreactjscreate-react-app

解决方案


this.someName 将成为“this”值的字段,在您的情况下,App 类。因此,它在整个 App 类中都可用,例如在渲染方法或任何其他实例方法中,例如 componentDidMount 或 foo()。

相反,如果你在渲染函数中声明变量,那么它的作用域是渲染函数,即它不会在实例方法中可用,例如componentDidMount。

如果您在 render 方法中定义变量,那么它只是一个方法中的变量,因此它将在每次调用 render 函数时被实例化,如果没有充分的理由产生额外的开销,这可能会很昂贵,然后在此声明变量将是一个明智的选择。

唯一想到的另一件事是更改类字段的值不会使渲染排队,而如果在 React 组件类的状态对象中定义给定值,那么这将触发新的渲染。

PS - 不是 100% 清楚你在问什么。


推荐阅读