Map function in react (err: TypeError: e.map is not a function)

陌路散爱 提交于 2021-02-09 10:57:07

问题


I want to render items from props, I can do it with initial state, but not with response from server. My render function :

 const { data } = this.props;
    return (
      <div >
          {data.map((item, index) =>
              <div key={index} className="row">
                  <span data = { data } className="number col-4 col-md-8">{item._id}</span>
                  <span data = { data } className="date col-4 col-md-2">{item.date}</span>
                  <span data = { data }  className="tag col-4 col-md-2">{item.tag}</span>
                  <div className="col-md-12 ">
                    {item.text}
                  </div>                
              </div>
          )}
      </div>
    )
  }

I get this mistake :

TypeError: e.map is not a function

response : Object {data: Array(12), status: 200, statusText: "OK", headers: Object, config: Object…}


回答1:


Had to change parent component change this:

  this.setState({
    data: response
  })

to

  this.setState({
    data: response.data
  })

I've tried to reach the data from the child component, but it din't work (probably because of the map function)




回答2:


It looks like your response is just the raw response. If you're using fetch, this is what the promise chain should look like:

fetch(fromMySource).then(resp => resp.json()).then(data => doSomething(data));

It looks like you might be trying to use resp directly which would make your data array look like the response object you posted in your question.




回答3:


You can use default value of data, when response is pending. In this time data is not defined

const { data = [] } = this.props;

Or use condition in  jsx:

render() {
   if (!data || !data.length) return null;
   ...
}



回答4:


Just add these words to your map function, Because you need check if the array was existed then execute map function

const { data } = this.props;
    return (
      <div >
          {data && data.length && data.map((item, index) =>
              <div key={index} className="row">
                  <span data = { data } className="number col-4 col-md-8">{item._id}</span>
                  <span data = { data } className="date col-4 col-md-2">{item.date}</span>
                  <span data = { data }  className="tag col-4 col-md-2">{item.tag}</span>
                  <div className="col-md-12 ">
                    {item.text}
                  </div>                
              </div>
          )}
      </div>
    )
  }


来源:https://stackoverflow.com/questions/45787301/map-function-in-react-err-typeerror-e-map-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!