簡體   English   中英

react native:是否可以將'array [0]'替換為'this.state'?

[英]react native : Is it possible to replace 'array[0]' with 'this.state'?

我正在嘗試console.log an array 我可以使用this.state代替硬編碼數組編號

例如,這是使用console.log一個帶有數字的數組的常用方法:

console.log(array[2], 'show array number 2')

有沒有辦法用this.state.number替換array[2]

我試過了,但是行不通。

this.state = {
              number:'2'}
console.log(array.this.state.number, 'show array with state')

如果要動態記錄陣列內容,請嘗試以下操作:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { arrayIndex: 0, array: [] };
  }

  upIndex = () => this.setState({ arrayIndex: this.state.arrayIndex + 1 });

  downIndex = () => this.setState({ arrayIndex: this.state.arrayIndex - 1 });

  render () {
    console.log(this.state.array[this.state.arrayIndex]);
    return (<div>...</div>);
  }
}

注意:您可以將upIndexdownIndexupIndex onClick回調按鈕上,以更改arrayIndex並注意檢查索引是否超出范圍。

你可以試試

this.setState({
    number: 2
}, () =>{
    console.log(array[this.state.number], 'show array with state')
})

數組是類似列表的對象,數組的索引為零,數組的第一個元素的索引為0,而最后一個元素的索引等於數組的length屬性的值減去1。使用無效的索引號將返回undefined 。 給定以下數組

const arr = ['this is the first element', 'this is the second element', 'this is the last element'];

要打印第一個元素,將使用索引0

 const arr = ['this is the first element', 'this is the second element', 'this is the last element']; console.log(arr[0]); 

要打印數組中的任何元素,請使用任何有效索引。

 const arr = ['this is the first element', 'this is the second element', 'this is the last element']; console.log(arr[1]); 

如果使用無效的索引,則將無法undefined

 const arr = ['this is the first element', 'this is the second element', 'this is the last element']; console.log(arr[3]); 

DEMO

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script> <div id="root"></div> <script type="text/babel"> class App extends React.Component { state = { items: ['this is the first element', 'this is the second element', 'this is the last element'], title: '' } render() { const buttons = this.state.items.map((btn, i) => <button onClick={() => this.setState((prevState) => { return { title: prevState.items[i] } })} key={i}>Item at index {i}</button>) return ( <div> <p>{this.state.title}</p> {buttons} </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); </script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM