在render函数后面写一个变量和在构造函数中写“this.name of variable”有什么区别?

What is the difference between writing a variable after the render function and writing " this.name of variable " in the constructor function?

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

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中主appclass的结构及其与前面代码写的位置的联系。

this.someName 将成为值 'this' 的字段,在您的情况下,应用程序 class。因此,它在您的整个应用 class 中都可用,例如在 render 方法或任何其他实例方法中,例如 componentDidMount 或 foo()。

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

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

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

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