Home >Web Front-end >JS Tutorial >react method to append data to array
The specific method is as follows:
(Free video tutorial: react video tutorial)
First render a random number, so that It changes every one second, and the effect is as follows:
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>数组追加元素</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="xpf"></div> <script type="text/babel"> class Xpf extends React.Component { constructor(props){ super(props); this.state = { random:Math.random() } } componentWillMount(){ setInterval(() => { this.setState({ random:Math.random() }) }, 1000); } render() { let {random} = this.state; return ( <div> <div> {random} </div> </div> ); } } ReactDOM.render( <Xpf />, document.getElementById('xpf') ); </script> </body> </html>
Note: There are two ways to update components: changes in props or state , and changing the state is generally done through the setState() method. Only when the state or props change, the render method can be called again, that is, the component updates
Put the generated random number into an array, the effect is as follows:
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>数组追加元素</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="xpf"></div> <script type="text/babel"> class Xpf extends React.Component { constructor(props){ super(props); this.state = { random:Math.random(), arr:[1,2,3] } } componentWillMount(){ setInterval(() => { this.setState({ random:Math.random(), arr:[...this.state.arr,Math.random()] }) }, 1000); } render() { let {random,arr} = this.state; return ( <div> <div> {random} </div> <ul> { arr.map((item,index)=>{ return ( <li key={index}>{item}</li>) }) } </ul> </div> ); } } ReactDOM.render( <Xpf />, document.getElementById('xpf') ); </script> </body> </html>
Use...this.state.arr to deconstruct arr, and then add the random number to it
Note: You cannot use arr: this.state.arr.push(Math.random()). You cannot use methods that modify the original array, such as push. You can use the concat method or ES6 array expansion syntax
Related recommendations: js tutorial
The above is the detailed content of react method to append data to array. For more information, please follow other related articles on the PHP Chinese website!