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⭐⭐⭐