关于javascript:如何将带有@符号的JSON传递给React中的props

How to pass JSON with @ symbol to props in React

本问题已经有最佳答案,请猛点这里访问。

我正在使用带有react的axios从数据库请求json数据。我能够获取json并将其分配给state并将其作为道具传递给我的应用中的子组件。我遇到的问题是json中的某些对象以'@'符号开头并引发语法错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    var Events = React.createClass({
    getInitialState: function() {
    return {
      events: [],
    }
  },
  componentDidMount: function() {
    var _this = this;
    this.serverRequest =
      axios
        .get("MY URL STRING HERE")
        .then(function(result) {
          _this.setState({
            events: result.data
          });
        })
  },
  componentWillUnmount: function() {
    this.serverRequest.abort();
  },
    render: function() {
        return (
           
                {this.state.events.map(function(event) {
                    return (
                       
                            <Event title={event.EventTitle} date={event.EventDate} description={event.EventDescription} presentor={event.EventPresenters} location={event.EventLocation} registered={event.registeredusercount} max_reg={event.EventMaximumAttendees} key={event.@unid} id={key} status={event.status} />
                       
                    )
                })};
           
        )
    }
});


我假设您的问题不是解析数据,而是React将对象作为prop传递下来?如果是这样,您应该能够通过带有括号符号的字符串动态访问属性,就像这样。

1
2
3
4
5
6
let foo = {'@bar': 'test'};
foo.@bar;
// => Uncaught SyntaxError: Invalid or unexpected token

foo['@bar'];
// => 'test'

对于您的组件,应为:

1
<Event key={event['@unid']} />