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⭐⭐⭐
  • 相关阅读:
    Git Bash 常用指令
    C/C++连接MySQL数据库执行查询
    question from asktom
    ORACLE AWR报告
    查看oracle表索引
    ORACLE数据库关闭与启动
    SYS vs SYSTEM and SYSDBA vs SYSOPER
    【面试】二叉树遍历的非递归实现
    快速排序的非递归实现
    MySQL数据库基础
  • 原文地址:https://www.cnblogs.com/surfer/p/11362264.html
Copyright © 2011-2022 走看看