2

This is peculiar.

I'm passing an array consisting of a single object to a React component's Render method:

let content = this.state.links.map(link => { // eslint-disable-line
  return (
    <li key={link._id}>
      <a href={link.link}>{link.title}</a>
    </li>
  );
});

return (
  <h3>
    <ul>
      {content}
    </ul>
  </h3>
);

This is the output of this.state.links :

[{"_id":"56f9b418657c2d2353611b0f","link":"https://facebook.github.io/flux/","title":"flux"}]

It's an array with one object. How come I'm getting this error?:

enter image description here

UPDATE: I've kinda found the problematic code:

It's fine going into here:

const _getAppState = () => { // eslint-disable-line return { links: LinkStore.getAll(), }; };

LinkStore.getAll() still returns an array with an object.

Then the next time we call the above function: onChange() { console.log('4. In the View', _getAppState()); // this.setState(_getAppState()); }

enter image description here

Still not totally sure when and how it transforms into a string. If you want to dig into the code and see for yourself, here is the repo.

8
  • 2
    what is the output of console.log(typeof this.state.links)? Commented Mar 28, 2016 at 23:07
  • It's coming out as a string! o.O Commented Mar 28, 2016 at 23:09
  • What does the compiled code look like? Commented Mar 28, 2016 at 23:25
  • Do you need to use JSON.parse to turn you links into an object. It seems based on your comment that links contains as string which does not have a map function. Try, where ever you are assigning this.state.links, to run JSON.parse(value) when assigning. Commented Mar 28, 2016 at 23:26
  • I created a jsfiddle.net/32be8Lwo/1 that shows the difference. Commented Mar 28, 2016 at 23:35

1 Answer 1

1

The return body from the server is still a JSON string. By doing console.log() on a JSON string the escape \ is removed in the console. It seems you thought the value was parsed, but in reality it wasn't. Run JSON.parse(body) on the response, it should work.

Example: https://jsbin.com/bomehafeki/1/edit?js,console

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.