const或let在React组件中 [英] const or let in React component

查看:305
本文介绍了const或let在React组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个React组件-是否笨-我想从商店中获取一些东西并将其放入变量中,以使我的代码更简洁.我应该使用const还是let?显然状态会改变.

Say I have a React component -- dumb or not -- and I want to grab something from the store and put it in a variable to make my code a bit more terse. Should I use const or let? Clearly the state will change.

这是我所谈论的例子.再次强调一下,myValues会在用户与我的应用进行交互时发生变化.

Here's an example of what I'm talking about. Again, I want to emphasize that myValues WILL change as user interacts with my app.

class MyComponent extends Component {

    render() {

        // Here, should I use const or let?
        const myValues = this.props.someData;

        return(
            <div>

            {myValues.map(item => (
                    <SomeOtherComponent key={item.id} data={item} />
                ))}

            </div>
        );
    };
}

function mapStateToProps(state) {
    return {
        someData: state.someValuesComingFromApi
    }
}

export default connect(mapStateToProps)(MyComponent)

推荐答案

const vs let主要与代码块中的更改"有关.仅在以下情况下才重要:

const vs let is mostly to do with "changing" in a code block. It only matters in situations like this:

const myValues = this.props.someData;
if (*some condition*) {
  myValues = [];
}

在这种情况下,您将需要使用let,因为您正在更改分配给变量myValues的值:

In this situation you would need to use let because you are changing the value assigned to the variable myValues:

let myValues = this.props.someData;
if (*some condition*) {
  myValues = [];
}

如果props.someData进行更改,则会触发组件的重新渲染.因此const vs let不起作用.整个render方法都将重新运行.

If props.someData is changing it will trigger a re-render of the component. So const vs let does not come in to play. The entire render method is re-run.

也就是说,在您描述的情况下,我使用const.除非您直接操纵变量的价值,否则请使用const.

So that said, I use const in the situations you are describing. Unless you are directly manipulating the valuable of a variable, use const.

这篇关于const或let在React组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆