Uncaught TypeError: this.state.data.map is not a function

I am new to React, have seen some similar problems, but have not found why this is happening. I get the message "Uncaught TypeError: this.state.data.map is not a function." Here is the code. Please help find what the problem is.

class Audienses extends React.Component { constructor (props) { super(props); this.state = { data: '' }; this.loadFromServer = this.loadFromServer.bind(this); this.childeDelete = this.childeDelete.bind(this); this.childeEdit = this.childeEdit.bind(this); } loadFromServer () { var xhr = new XMLHttpRequest(); xhr.open('get', this.props.url, true); xhr.onload = function() { var data = JSON.parse(xhr.responseText); this.setState({ data: data }); }.bind(this); xhr.send(); } componentDidMount() { this.loadFromServer(); } render () { var audienses = this.state.data.map((value, index) => ( <OneElement key={value.id} audience={value.audience} description={value.description} /> )); /* or like this var audienses = this.state.data.map(function(s) { <OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} /> }).bind(this); */ return <div> <h1>Audiences</h1> <table id="services"> <tr> <th>Audience</th> <th>Description</th> <th></th> <th></th> </tr> <tbody> {audienses} </tbody> </table> </div>; } } 
+14
source share
3 answers

Your initial state is data String ., String has no .map method, you need to change the initial state from '' to []

 this.state = { data: [] }; 
+33
source

.map not applicable to a String object. Think about changing the "data" in the array. .map is a method that calls a function for each element of the array .

+6
source

I have the same error in reactive reduction.

the problem was that when I add a new product on the add / product page and click the "Back" button, this error is displayed on the component of the home page

home_container.js: 8 Uncaught TypeError: products.product.map is not a function

 renderItems = (products) => ( products.product ? products.product.map(item => ( <ProductItem {...item} key = { item._id } /> )) : null ) 

decision

I pass {} instead of [] from the host server

Thus, if you have this type of error in response-redux, then first check what you are passing from the server to this field, and also check the reducers of this particular component.

0
source

All Articles