简体   繁体   中英

React.js this.props.data.map() is not a function

I'm messing around with react and trying to parse and render a json object. Right now, I'm just setting it with a hard-coded object for testing and not getting it from an ajax call.

<script type="text/jsx">

var Person = React.createClass({
render: function() {
  return (
    <div>
      <p className="personName"></p>
      <p className="personSA1"></p>
      <p className="personSA2"></p>
      <p className="zip"></p>
      <p className="state"></p>
      <p className="country"></p>
    </div>
  );
 }
});

var PersonDiv = React.createClass({
render: function() {
  var personNodes = this.props.data.map(function(personData){
    return (
      <Person
        personName={personData.person.firstname}
        personSA1={personData.person.street1}
        personSA2={personData.person.street2}
        zip={personData.person.zip}
        state={personData.person.state}
        country={personData.person.country}>
      </Person>
    )
});
return (
  <div>
    {personNodes}
  </div>
);
}
});

React.render(
 <PersonDiv data={data} />,
document.getElementById('jsonData')
);

I'm setting the data variable with

<script>
  var data = "[" + '<%=data%>' + "]";
</script>

The data object is one that I'm creating on the java side of a portlet. I know that the json is valid, because I can use JSON.parse(json) to parse and traverse the string, but I keep getting that map() is not a function.

It appears that your data is not a json object, it is a string. You probably need to run data = JSON.parse(data); to convert your data into an actual javascript object to be able to use it. An easy test for this would be to run

<script>
  var data = "[" + '<%=data%>' + "]";
  console.log(data);
  console.log(JSON.parse(data));
</script>

You should notice the difference.

You are passing result of console.log as first parameter to React.render :

React.render(
 console.log("inside render"),
 <PersonDiv data={data} />,
document.getElementById('jsonData')
);

It should be like:

console.log("will render");
React.render(
     <PersonDiv data={data} />,
    document.getElementById('jsonData')
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM