繁体   English   中英

如何将新获取的项目添加到 React Native 的列表顶部?

[英]How to add newly fetched items to the top of the list in react native?

在我的项目中,我从服务器和card列表中获取json数据。但我面临的问题是每当向json data添加新项目时,新项目将呈现在现有card的底部。但是我所面临的问题想要它应该填充在现有cards的顶部。那么我该怎么做?以下是我的获取和列出卡片的示例代码。请帮助我找到解决方案。任何帮助都将非常值得赞赏。谢谢。

    componentWillMount(){

    fetch(GLOBAL.NEW_WORK_REQUEST,{
          method: 'POST',
          headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body:JSON.stringify({
            name:"name"
          })
        })
        .then((response) => response.json())
        .then((responseData) =>
        {
          this.setState({
            work_rq :responseData.data
          })
        });
      }
    }
   ...
   ...
   <View>
          {this.state.work_rq.map(a => (
           <CardSection>
               <TouchableOpacity>
                   <Text style={{fontSize:18,padding:8}}>Work Category:{a.work_type}</Text>
               </TouchableOpacity>
           </CardSection>
              ))}
              </View>

您可以使用两种方式

1) 使用array.reverse() ,不会使用两个数组。

2)使用两个数组当你在这里添加新数据时将使用第二个数组我使用2个状态newdatadata ,其中newdata位于顶部

像这样,(第二种方法)

    constructor(props) {
    super(props);
    this.state = { data: [1, 2, 3], newData: [] };
  }
  handleClick() {
    var data = Math.random();
    this.setState({ newData: this.state.newData.concat(data) });
  }
  render() {
    console.log(this.state);
    return (
      <div>
        {this.state.newData && this.state.newData.reverse().map(a => {
          return <div>{a}</div>
        })}
        {this.state.data.map(a => {
          return <div>{a}</div>
        })}
        <button
          className={this.state.isToggleOn ? 'ON' : 'OFF'}
          onClick={(e) => this.handleClick(e)}>

          {this.state.isToggleOn ? 'ON' : 'OFF'}

        </button>
      </div>
    );
  }

演示

第一种方法你可以简单地做 array.reverse 并且所有数据都将附加到 reverse()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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