Reactjs Array.slice(开始,结束)不起作用

问题描述 投票:-1回答:1

我对slice()功能有问题。

我的代码:

constructor(props){
  super(props);
  this.state({
    data: props.data
  })
}

//my function
onSliceData = () => {
  let data = this.state.data;
  let sliceData = data.slice(0,5);
  return sliceData;
}

我的问题是我的函数没有返回任何内容。当我在[[onSliceData中的console.log(data)时,我收到这样的结果:

“”当我console.log(sliceData)我刚收到[]“”我尝试使用Object.keys将数据转换为数组,但可能无法正常工作。我需要一些帮助。
reactjs slice
1个回答
0
投票
确保所接收的道具具有数据(是一个数组)

在构造函数中:

constructor(props){ super(props); this.state = { // assign the state with an js object instead of calling it as a func. data: props.data } }

尝试一下:

onSliceData = () => { let data = [...this.state.data]; // spreading will return a new array let sliceData = data.slice(0,5); return sliceData; }

© www.soinside.com 2019 - 2024. All rights reserved.