zoukankan      html  css  js  c++  java
  • ES6中的Export/import操作的是引用

    以下以react中的一个“Fruit store”的组件为例来验证上述结论:

    1. constants.js

    export const fruit = ['grape', 'apple', 'orange'];

    2. Fruit.js

    import React from 'react';
    import {fruit} from './constants';
    class Fruit extends React.Component{
        sayHi(){
            alert('hi, I am a fruit!');
        }
    
        updateState(){
            console.log('updateState executed');
            this.setState({
                fruit
            });
        }
    
        render(){
            console.log('fruit render executed');
            const myStyle={
                color: 'red',
                fontWeight: 'bold'
            }
            return <div style={myStyle}>I am a fruit store, I sell:
                <ul>
                    {fruit.map( el => <li>{el}</li> )}
                </ul>
            </div>
        }
    }
    export default Fruit;

    3. TodoApp.js

    import React from 'react';
    import {view as Todos} from './todos/';
    import {view as Filter} from './filter/';
    import PersonHoc from './hoc/PersonRemovedUser';
    import Person from './hoc/Person';
    import {fruit} from './hoc/constants';
    import Fruit from './hoc/Fruit';
    
    
    class TodoApp extends React.Component {
      componentDidMount(){
        this.fruit.sayHi();
      }
      handleClick = ()=>{
        fruit.push('watermelon');
        this.fruit.updateState();
      }
      render(){
        return (
          <div>
            <button onClick={this.handleClick}>Todo CLICK!</button>
            <Fruit 
              ref={(w) => {
                return this.fruit = w;
              }}/>
          </div>
        );
      }
    }
    
    export default TodoApp;

    在index.js中加载TodoApp组件,并点击按钮可见Fruit组件内的list item一直在增加,说明在TodoApp内修改了fruit对象,会影响在Fruit内消费的fruit对象,二者为同一引用。

     

    路漫漫其修远兮,吾将上下而求索。 May stars guide your way⭐⭐⭐
  • 相关阅读:
    codeAnalyze_函数赋值给另一个函数的形参
    js_new关键字创建对象的五个步骤
    codeRecord_bind
    js_活动对象与变量对象的区别
    将linux的随机ip固定为设置的固定ip
    Springcloud总结
    Jackson的使用
    Lucene的初步了解和学习
    Shiro安全框架
    关于xpath中的tbody
  • 原文地址:https://www.cnblogs.com/surfer/p/11362264.html
Copyright © 2011-2022 走看看