React

时间:2019-09-16 08:03:53

标签: javascript reactjs api fetch

React的新手,我目前正在尝试使用API​​中的数据创建数据表。 我想先进行提取,然后再运行第一个(id)的响应,以完成我的表。

这是我的代码:

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

        this.state = {
            user: {},
            data: []
        };
    }

    componentDidMount() {
        this.setState({
            user: JSON.parse(localStorage.getItem('user'))
        }, function () {
            this.loadAllObjectsInfo()
        });
    }

    // Fetch all object info in order to fill the table
    loadAllObjectsInfo() {
        const requestOptions = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'bbuser': this.state.user.userId,
                'bbtoken': this.state.user.secret
            },
        };

        fetch('https://xxxxx/api/objects', requestOptions)
            .then(response => response.json())
            .then((data) => {
                this.setState({ data: data })
            })

    }

有了此代码,我有了要呈现表的数据,但是我需要运行另一个访存来获取其他信息,其ID来自第一个请求。

如何执行嵌套的提取请求?

非常感谢

马修

4 个答案:

答案 0 :(得分:5)

您可以使用const Weather = ({capital}) => { const [weather, setWeather] = useState({location:{}, current: {}}); const [loading, setLoading] = useState(true); const key = 'mykey' const url = `http://api.weatherstack.com/current?access_key=${key}&query=${capital}` useEffect(() => { axios.get(url) .then(response => { console.log('promise fullfilled') setLoading(false); setWeather(response.data) }) }, []) return loading ? <p>Loading...</p> : ( <div> <h1>Weather in {weather.location.name}</h1> <h2>temperature: {weather.current.temperature} </h2> <img src = {weather.current.weather_icons} /> <h2>wind: {weather.current.wind_speed} kph direction {weather.current.wind_dir}</h2> </div> ) } 轻松管理它:

async/await

您可以了解有关async function的更多信息。

答案 1 :(得分:3)

您可以编写以下代码。

fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((res1) => {

    fetch('https://xxxxx/api/objects', requestOptions)
    .then(response => response.json())
    .then((res2) => {
        this.setState({ data: res2 });
    });

});

希望这对您有用!

答案 2 :(得分:3)

@JourdanM,您应该从fetch处理程序之一返回一个新的then请求。我为您做了一个简单的摘要。没有数据验证器和微调器。这是一个简单的展示。 =)

一个fetch请求返回一个诺言,您可以通过简单地从then处理程序中返回它们来链接诺言。这是一篇很好的文章,其中有很多示例:https://javascript.info/promise-chaining

function fetchUser (user) {
  return fetch(`https://api.github.com/users/${user.login}`)
}

class User extends React.Component {
  state = {
    user: null
  }

  componentDidMount () {
    fetch("https://api.github.com/users")
      .then(response => response.json())
      .then(users => fetchUser(users[0]))
      .then(response => response.json())
      .then(user => {
        this.setState({user})
      })
  }
  
  render () {
    return (
      <div>
        <pre>{JSON.stringify(this.state.user, null, 2)}</pre>
      </div>
    )
  }
}

ReactDOM.render(<User />, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

答案 3 :(得分:2)

您也可以像下面一样使用axios

axios.post(url, data, header).then(res => {
        if(res.status === 200){
             console.log('1st data')
            axios.post(url, data, header)
                .then(response => {
                    if (response.status === 200) {
                        console.log('2nd data')
                    } else {
                        console.log('2nd error')
                    }
                });

        }else{
            console.log('1st error')
        }
    });