简体   繁体   English

reactjs-从api获取数据

[英]reactjs - fetching data from api

I'm still fairly new to ReactJS, and through the help of the great SO community, I've been building a small exercise that moves items back and forth between two components on a click. 我对ReactJS还是很陌生,并且在一个很棒的SO社区的帮助下,我正在构建一个小练习,单击一下即可在两个组件之间来回移动项目。 These items are coming from data in a json array items=[] that I hard coded into the file. 这些项目来自我硬编码到文件中的json数组items=[]中的数据。 I was wondering how I would go about getting the data from an api, I've read the documentation and know I should do it via the componentDidMount method, however I am getting stuck figuring out how to set the state in the method. 我想知道如何从api中获取数据,我已经阅读了文档,并且知道我应该通过componentDidMount方法来进行处理,但是我一直在想办法在方法中设置状态。 The code is below... 代码如下...

class SingleItem extends React.Component {
render() {
    let data = this.props.data;

    return (
        <li onClick={this.props.onClick}>
            <div> {data.name} </div>
        </li>
    );
  }
}

class ItemList extends React.Component {
   render() {
    let itemArr = this.props.allItems;
    let myItems = this.props.items;
    let handleEvent = this.props.handleEvent;

    let listItems = itemArr.map((itemObj) => {
        if (!myItems.includes(itemObj.id)) return null;

        return <SingleItem
            key={itemObj.id}
            data={itemObj}
            onClick={() => handleEvent(itemObj.id)}
        />;
    });

    return (
        <ul>
            {listItems}
        </ul>
    );
  }
}

 class App extends React.Component {
   constructor(props) {
     super(props);

     this.state = {
        data: [],
        boxOne: props.items.map(item => item.id), // init the boxes with 
 itemIds
        boxTwo: []
    };

    this.handleEvent = this.handleEvent.bind(this);
}

handleEvent(itemId) {
    const isInBoxOne = this.state.boxOne.includes(itemId);

    // Heres the magic, if the item is in the first Box, filter it out,
    // and put into the second, otherwise the other way around..
    this.setState({
        boxOne: isInBoxOne
            ? this.state.boxOne.filter(i => i !== itemId)
            : [ ...this.state.boxOne, itemId ],
        boxTwo: isInBoxOne
            ? [ ...this.state.boxTwo, itemId ]
            : this.state.boxTwo.filter(i => i !== itemId)
    });
}
render() {
    return (
        <div className="wrapper">
            <div className="box">
                <ItemList handleEvent={this.handleEvent} items={this.state.boxOne} allItems={this.props.items} />
            </div>
            <div className="box">
                <ItemList handleEvent={this.handleEvent} items={this.state.boxTwo} allItems={this.props.items} />
            </div>
        </div>
    );
  }
 };

var items = [
  {name: "Item 1", id: 1},
  {name: "Item 2", id: 2},
  {name: "Item 3", id: 3},
  {name: "Item 4", id: 4},
  {name: "Item 5", id: 5},
  {name: "Item 6", id: 6}
 ]

ReactDOM.render(
   <App items={items} />,
   document.getElementById('root')
 );

You could do that easily with axios 您可以使用axios轻松做到这一点

componentDidMount() {
  axios.get('http://myapi.com/myrequest')
    .then((res) => {       
      this.setState({ data:res.myvalue }); // change state
  })
}

However, to do a more complex app with "global states" between components, dedicated API, etc.. You should use Redux or Meteor 但是,要使用组件,专用API等之间的“全局状态”来做一个更复杂的应用程序。您应该使用ReduxMeteor

嗨,您可以使用从Java脚本获取api进行api调用,也可以使用promise处理结果。

You can directly call your HTTP in componentDidMount yes. 您可以在componentDidMount yes中直接调用HTTP。 But as your app grows you will want to isolate this logic from the components. 但是随着您的应用程序的增长,您将需要将此逻辑与组件隔离。 Thus your component will be more reusable and more maintainable. 因此,您的组件将更可重用且更易于维护。 Just wait for the promise to fulfill before setting your state with the result. 只需等待诺言兑现,然后再设置结果状态即可。

axios.get('/api/url')
  .then(function (response) {
    this.setState({data: response.data})
  })
  .catch(function (error) {
    this.setState({data: [], error: true})
  })

About the library to make the HTTP requests, you can use axios , or superagent . 关于发出HTTP请求的库,您可以使用axiossuperagent Anyway I suggest you to use a library that works both on server and client site. 无论如何,我建议您使用在服务器和客户端站点上都可以使用的库。 So If you want your app to be isomorphic/universal ( rendered by a nodeJS server ), you won't be in trouble. 因此,如果您希望您的应用程序是同构的/通用的(由nodeJS服务器呈现),那么您就不会遇到麻烦。

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

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