代码之家  ›  专栏  ›  技术社区  ›  Oktam Yaqubov

React JS-类型错误:此.state.data.map不是函数

  •  0
  • Oktam Yaqubov  · 技术社区  · 6 年前

    现在我正在尝试使用axios和React JS从API获取数据。但是当我使用这个代码时,我得到了一个错误:

    TypeError: this.state.countries.map is not a function
    

    我有状态数据:[]并且我正在尝试设置状态中URL的值。所以我的代码是这样的:

    //get user token
    const GetTokens = 'Bearer '.concat(localStorage.getItem('token'));
    export default class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            countries: [],
            response: {}
        }
     }
       componentDidMount() {
        axios.get(apiUrl + '/country-lists', { headers: { Authorization: GetTokens } })
            .then(response => response.data).then(
                (result) => {
                    this.setState({
                        countries: result
                    });
                },
                (error) => {
                    this.setState({ error });
                }
            )
    }
    

    在我的渲染中:

    {this.state.countries.map(list => (
    {list.name}
     ))}
    

    我也试过这样。

    render() {
        const (countries ) = this.state
        const (countries = []) = this.state
    

    在我看来,我没有错,当得到一个令牌和参考地图。但我不知道我在哪里犯的错。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Tony Ngo    6 年前

    通过看你的控制台.log我想你应该用 result.data

     componentDidMount() {
        axios.get(apiUrl + '/country-lists', { headers: { Authorization: GetTokens } })
            .then(response => response.data).then(
                (result) => {
                    this.setState({
                        countries: result.data
                    });
                },
                (error) => {
                    this.setState({ error });
                }
            )