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⭐⭐⭐
  • 相关阅读:
    03-温故知新(下载网络资源)
    02-Inet套接字地址
    01-InetAddress常用方法
    递归删除文件夹跟拷贝文件夹
    File中常用的方法
    简单日志功能的实现
    简单二分查找算法
    应用打开其xlspptdoc等
    PPT文件分析摘记
    ReactNative小笔记
  • 原文地址:https://www.cnblogs.com/surfer/p/11362264.html
Copyright © 2011-2022 走看看