简体   繁体   中英

Why initializing 1D array and 2D array to state in React js behaves differently

Example 1

 const arr = ["a","b","c","d"] class Alphabate extends React.Component{ constructor(props){ super(props) this.state = {alpha:[...arr]} this.state.alpha[0] = "Changed" console.log(`inside consructor arr = ${arr}`) } render(){ return <div> {this.state.alpha.map( x=><h3>{x}</h3> )} </div> } } ReactDOM.render(<Alphabate />, document.getElementById("root"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

In this example 1 browser displays Changed b c d and console logs "inside consructor arr = a,b,c,d"

 const arr = [["a","b"], ["c","d"]] class Alphabate extends React.Component{ constructor(props){ super(props) this.state = {alpha:[...arr]} this.state.alpha[0][0] = "Changed" console.log(`inside consructor arr = ${arr}`) } render(){ return <div> {this.state.alpha.map( x=>x.map( y=><h3>{y}</h3> ))} </div> } } ReactDOM.render(<Alphabate />, document.getElementById("root"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

in this example browser displays Changed b c d and console logs "inside consructor arr = Changed,b,c,d"

So my question is: why 1D array passed by value and 2D array pass by reference although i have passed copy of array [...arr] not the array

JavaScript doesn't have "2d" arrays. It has arrays of arrays. When you do this:

this.state = {alpha:[...arr]}

...you're only making a copy of the outer array; it still contains references to the same inner arrays that the original arr had. So when you change the contents of those inner arrays, you see that change regardless of which outer array you look through to get to the inner one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM