Javascript 如何使用componentDidMount()发出多个axios.get()请求,并将响应值1分配给2?

Javascript 如何使用componentDidMount()发出多个axios.get()请求,并将响应值1分配给2?,javascript,reactjs,rest,promise,axios,Javascript,Reactjs,Rest,Promise,Axios,我正在尝试用WordPressRESTAPI构建一个web应用程序 我正在向端点发出初始GET请求,并通过res.data解析以获取一些值。但是,其中一个值featured_media是我试图发出的第二个GET请求的参数。我发现很难在第二个get请求中从该状态获取该值 这里是美国 state = { graduatepost: {}, category: '', featured_media: '', imgURL: '',

我正在尝试用WordPressRESTAPI构建一个web应用程序

我正在向端点发出初始GET请求,并通过
res.data
解析以获取一些值。但是,其中一个值
featured_media
是我试图发出的第二个GET请求的参数。我发现很难在第二个get请求中从该状态获取该值

这里是美国

state = {
        graduatepost: {},
        category: '',
        featured_media: '',
        imgURL: '',
        isLoaded: false
    }
下面是
componentDidMount()

第一次获取请求:
http://localhost:8000/wp-json/wp/v2/blog/${this.props.match.params.id}

第二次获取请求:
http://localhost:8000/wp-json/wp/v2/media/${featured_media}

如您所见,第二个请求需要值
featured\u media
,该值在第一个GET请求的响应中

我正在像这样渲染组件

render() {
        const { graduatepost, category, isLoaded, featured_media, imgURL } = this.state;
        if(isLoaded) {
            return (
                <Styles>
                    <Fragment>
                        <Link to='/graduate-posts'>Go Back</Link> // Ignore this
                        <hr />
                        <h1>{graduatepost.title.rendered}</h1>
                        <div dangerouslySetInnerHTML={{__html: graduatepost.content.rendered}}></div>
                        <h4>Category: {category}</h4>
                        <h4>featured_media: {featured_media}</h4>
                        <h4>imgURL: {imgURL}</h4>
                    </Fragment>
                </Styles>
            )
        }
        return <h3>Loading...</h3> // Ignore this
    }
我假设这是因为
featured\u media
为空/未定义,但我无法确定如何从第一个GET请求response中提取该值

这看起来似乎很明显,但我对一起使用React.js和API还比较陌生。非常感谢你的帮助


谢谢。

您尝试过异步功能吗


可能在第一个axios.get的响应中请求它。它不起作用的原因是因为
this.setState
是React中的一个异步函数,因此当您访问它的正下方时,它是
未定义的

尝试以下方法:

axios.get(`http://localhost:8000/wp-json/wp/v2/blog/${this.props.match.params.id}`)
  .then((res) => {
    const state = {
             graduatepost: res.data,
             category: res.data.categories[0],
             featured_media: res.data.featured_media,
             isLoaded: true
    }
    this.setState(state)
    return axios.get(`http://localhost:8000/wp-json/wp/v2/media/${state.featured_media}`);
  })
  .then((res) => {
    // do something with res
  })
  .catch((err) => {
    // handle err
  });

立即访问设置数据的最佳方法是使用。

this.setState
接受回调作为其第二个参数(
setState(updater,[callback])
),因此我们应该在
callback
语句中提出第二个请求。

您的代码应该是这样的:

axios
.得到(`http://localhost:8000/wp-json/wp/v2/blog/${this.props.match.params.id}`)
。然后((res)=>
这是我的国家(
{
研究生职位:研究数据,
类别:res.data.categories[0],
特色媒体:res.data.featured\u媒体,
isLoaded:是的,
},
() =>
axios
.得到(
`http://localhost:8000/wp-json/wp/v2/media/${this.state.featured_media}`
)
。然后((res)=>{
这是我的国家({
imgURL:res[0]。data.media\u details.size.full.source\u url,
isLoaded:是的,
})
})
)
)
.catch((err)=>console.log(err))

我准备了一个示例,其中显示了所有用户,如果单击查看帖子按钮,它将显示该用户的所有帖子

App.js

class App extends React.Component {
    render() {
        return (
            <Router>
                <div>
                    <ul>
                        <li>
                            <Link to="/">Home</Link>
                        </li>
                        <li>
                            <Link to="/posts">Posts</Link>
                        </li>
                    </ul>
                    <hr/>
                    <Switch>
                        <Route exact path="/">
                            <UserList/>
                        </Route>
                        <Route path="/posts">
                            <PostListPageByUser/>
                        </Route>
                    </Switch>
                </div>
            </Router>
        );
    }
}
export default App;
类应用程序扩展了React.Component{
render(){
返回(
  • 帖子

); } } 导出默认应用程序;
用户列表组件

import React from 'react';
import axios from 'axios';
import PostListPageByUser from "./PostListPageByUser";
import {withRouter} from "react-router-dom";

class UserList extends React.Component {
    state = {
        users: [],
        showPostList: false,
        user: {}
    };

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                console.log(users);
                this.setState({users});
            })
    }

    handleClick = (user) => {
        console.log(user);
        this.setState({showPostList: true, user: user});
        this.props.history.push({
            pathname: '/posts',
            user: user
        });
    };

    render() {
        return (
            <div>
                <ul>
                    {this.state.users ? this.state.users.map(user => <div key={user.id}>
                        <span style={{minWidth: 400}}>{user.name} </span>
                        <button onClick={() => {
                            this.handleClick(user)
                        }}>See Posts
                        </button>
                    </div>) : null}
                </ul>
                {this.state.showPostList ? <PostListPageByUser user={this.state.user}/> : null}
            </div>
        )
    }
}

export default withRouter(UserList);
import React from "react";
import axios from 'axios';
import {withRouter} from "react-router-dom";

class PostListPageByUser extends React.Component {
    signal = axios.CancelToken.source();
    state = {
        posts: [],
    };

    componentDidMount() {
        if(!this.props.location.user){
            alert('Please click see posts button');
            this.props.history.push('/');
            return;
        }
        axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${this.props.location.user.id}`, {
            cancelToken: this.signal.token,
        })
            .then(res => {
                this.setState({posts: res.data});
                console.log(res.data, 'Posts');
            }).catch(err => {
            console.log(err);
        });
    }

    render() {
        return (
            <div>
                <ul>
                    {
                        this.state.posts ? this.state.posts.map(post => <li key={post.id}>{post.title}</li>) : null
                    }
                </ul>
            </div>
        )
    }
}

export default withRouter(PostListPageByUser);
从“React”导入React;
从“axios”导入axios;
从“/PostListPageByUser”导入PostListPageByUser;
从“react router dom”导入{withRouter};
类UserList扩展了React.Component{
状态={
用户:[],
showPostList:false,
用户:{}
};
componentDidMount(){
axios.get(`https://jsonplaceholder.typicode.com/users`)
。然后(res=>{
const users=res.data;
console.log(用户);
this.setState({users});
})
}
handleClick=(用户)=>{
console.log(用户);
this.setState({showPostList:true,user:user});
这个。道具。历史。推({
路径名:'/posts',
用户:用户
});
};
render(){
返回(
    {this.state.users?this.state.users.map(user=> {user.name} { this.handleClick(用户) }}>见帖子 ):null}
{this.state.showPostList?:null} ) } } 使用路由器导出默认值(用户列表);
PostListByUser组件

import React from 'react';
import axios from 'axios';
import PostListPageByUser from "./PostListPageByUser";
import {withRouter} from "react-router-dom";

class UserList extends React.Component {
    state = {
        users: [],
        showPostList: false,
        user: {}
    };

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                console.log(users);
                this.setState({users});
            })
    }

    handleClick = (user) => {
        console.log(user);
        this.setState({showPostList: true, user: user});
        this.props.history.push({
            pathname: '/posts',
            user: user
        });
    };

    render() {
        return (
            <div>
                <ul>
                    {this.state.users ? this.state.users.map(user => <div key={user.id}>
                        <span style={{minWidth: 400}}>{user.name} </span>
                        <button onClick={() => {
                            this.handleClick(user)
                        }}>See Posts
                        </button>
                    </div>) : null}
                </ul>
                {this.state.showPostList ? <PostListPageByUser user={this.state.user}/> : null}
            </div>
        )
    }
}

export default withRouter(UserList);
import React from "react";
import axios from 'axios';
import {withRouter} from "react-router-dom";

class PostListPageByUser extends React.Component {
    signal = axios.CancelToken.source();
    state = {
        posts: [],
    };

    componentDidMount() {
        if(!this.props.location.user){
            alert('Please click see posts button');
            this.props.history.push('/');
            return;
        }
        axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${this.props.location.user.id}`, {
            cancelToken: this.signal.token,
        })
            .then(res => {
                this.setState({posts: res.data});
                console.log(res.data, 'Posts');
            }).catch(err => {
            console.log(err);
        });
    }

    render() {
        return (
            <div>
                <ul>
                    {
                        this.state.posts ? this.state.posts.map(post => <li key={post.id}>{post.title}</li>) : null
                    }
                </ul>
            </div>
        )
    }
}

export default withRouter(PostListPageByUser);
从“React”导入React;
从“axios”导入axios;
从“react router dom”导入{withRouter};
类PostListPageByUser扩展React.Component{
signal=axios.CancelToken.source();
状态={
员额:[],
};
componentDidMount(){
如果(!this.props.location.user){
警报(“请点击查看帖子按钮”);
this.props.history.push('/');
返回;
}
axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${this.props.location.user.id}`{
cancelToken:this.signal.token,
})
。然后(res=>{
this.setState({posts:res.data});
console.log(res.data,“Posts”);
}).catch(错误=>{
控制台日志(err);
});
}
render(){
返回(
    { this.state.posts?this.state.posts.map(post=>
  • {post.title}
  • ):null }
) } } 使用路由器导出默认值(PostListPageByUser);
这是否回答了您的问题?
import React from "react";
import axios from 'axios';
import {withRouter} from "react-router-dom";

class PostListPageByUser extends React.Component {
    signal = axios.CancelToken.source();
    state = {
        posts: [],
    };

    componentDidMount() {
        if(!this.props.location.user){
            alert('Please click see posts button');
            this.props.history.push('/');
            return;
        }
        axios.get(`https://jsonplaceholder.typicode.com/posts?userId=${this.props.location.user.id}`, {
            cancelToken: this.signal.token,
        })
            .then(res => {
                this.setState({posts: res.data});
                console.log(res.data, 'Posts');
            }).catch(err => {
            console.log(err);
        });
    }

    render() {
        return (
            <div>
                <ul>
                    {
                        this.state.posts ? this.state.posts.map(post => <li key={post.id}>{post.title}</li>) : null
                    }
                </ul>
            </div>
        )
    }
}

export default withRouter(PostListPageByUser);