两种功能有什么区别?

时间:2018-12-04 10:18:43

标签: javascript reactjs axios

app.js

import React from 'react';
import ClubDetail from './ClubDetail';

class ClubList extends React.Component {

    changeJSX() {
        return this.props.clubs.map((club) => {
            return (
                <div key={club.usid}>
                    <ClubDetail 
                        clubName={club.name} 
                        />
                    <button 
                        className="ui teal basic button"
                        onClick={(event) => this.props.findClub(event, 
                        club.name)}>
                    View</button>
                    <button 
                        className="ui violet basic button"
                        onClick={(event) => 
                        this.props.findMembership(event, club.name)}>
                    Membership</button>
                </div>
            );
        })
    }

    render() {
        return (
            <div className="ui secondary vertical pointing menu">
                {this.changeJSX()}
            </div>
         );

    }
};

export default ClubList;

这是我的app.js文件。 我想在这里使用findClub函数和findMember函数。 以上功能存在于父组件中。


import axios from ('axios');
...
    findClub = async (event, id) => {
        console.log(id);
        const findClub = await axios.get('/club/club/', {
            params: {
                name : id
            }
        }).then(response => {
            let club = response.data.findclub;
            this.setState({clubName: club.name , clubIntro: club.intro, 
            seleted: 'create'});
        });
    }

    findMembership = async (event, id) => {
        console.log(id);
        const findMembership = await 
        axios.get('/clubMembership/clubMembership', {
            params: {
                name : id
            }
        }).then(response => {
            console.log('findMembership is here')
        })
    }
    ...

在以上两个函数中,console.log(id);在findClub中有一个返回值,但是在undMembership中的console.log(id)没有返回值。

1 个答案:

答案 0 :(得分:1)

示例中的异步等待模式未始终应用。

基本上的想法是,您可以编写随后的链接,例如同步代码:

const response = await axios.get('/club/club/', {
    params: {
        name : id
    }
});

let club = response.data.findclub;
this.setState({clubName: club.name , clubIntro: club.intro, seleted: 'create'});

在这种情况下,您将使用await调用的返回值。