Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

reactjs - const or let in React component

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.

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

const is a signal that the variable won’t be reassigned.

let is a signal that the variable may be reassigned

Additional things to ponder:

  • Use const by default
  • Use let only if rebinding is needed
  • const does not indicate that a value is ‘constant’ or immutable.

    const foo = {};
    foo.bar = 10;
    console.log(foo.bar); // --> 10
    

    Only the binding is immutable. ie using an assignment operator or a unary or postfix -- or ++ operator on a const variable throws a TypeError exception

  • ES6 const and let are hoisted too. Although the identifiers has the same memory reference from compile time, they cannot be accessed before declaration in the code. (but not as we thought the declaration would be physically moved to the top in the scope) ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...