【问题标题】:How to add newly fetched items to the top of the list in react native?如何在本机反应中将新获取的项目添加到列表顶部?
【发布时间】:2019-06-06 23:34:17
【问题描述】:

在我的项目中,我从服务器获取json 数据并在card 中列出。但我面临的问题是,每当将新项目添加到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>

【问题讨论】:

    标签: javascript json react-native fetch jsx


    【解决方案1】:

    你可以通过两种方式来实现

    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>
        );
      }
    

    Demo

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

    【讨论】:

    • 所以在我的情况下,我可以在responseData.data 上执行array.reverse 吗?
    • 你可以,但这会以反向模式呈现所有数据
    • 是的,这意味着新添加的项目将是第一个元素,对吧?
    猜你喜欢
    • 2017-01-11
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    相关资源
    最近更新 更多