I have (e.g.) two components in React. The first, app.js, is the root component. It imports some JSON data and puts it in its state. This works fine (I can see it in the React devtools).

import data from '../data/docs.json';

class App extends Component {
  constructor() {
    super();
    this.state = {
      docs: {}
    };
  }
  componentWillMount() {
    this.setState({
      docs: data
    });
  }
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={Wrapper}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
          <Route path="/docs" component={Docs} />
        </Route>
      </Router>
    );
  }
}

第二个是docs.js,用于显示这JSON个数据.要做到这一点,它需要访问app.js中的state.现在它出错了,我知道为什么(this不包括app.js).那我怎么才能把stateapp.js转到docs.js呢?

class Docs extends React.Component {
    render() {
        return(
            <div>
                {this.state.docs.map(function(study, key) { 
                    return <p>Random text here</p>; 
                })}
            </div>
        )
    }
}

推荐答案

正确的方法是将状态传递为propsDocs组件.

然而,因为您使用的是React Router,所以可以以一种稍微不同的方式访问它:this.props.route.param而不是默认的this.props.param

因此,您的代码应该大致如下所示:

<Route path="/docs" component={Docs} docs={this.state.docs} />

and

{this.props.route.docs.map(function(study, key) { 
    return <p>Random text here</p>; 
})}

Json相关问答推荐

为什么terraform不缩小这个策略JSON?'

为什么JQ筛选器不将原始输入打印为$var|.';文档?

Golang返回的JSON顶级字段是可变的.如何在 struct 中使用

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

GO KaZaam转换返回意外结果

如何在改装Android中将ResponseBody转换为JSONObject

使用自定义类型在Golang中解析JSON数组

JQ:获取该值的较短语法是什么

交换键和数组值,将旧键转换为新数组值,使用 jq

当 JSON 字段名称有空格时,ABAP 中的 JSON 反序列化

go 语言中的 JSON 到 XML

VBA-JSON 嵌套集合解析为 Excel

JOLT 转换仅过滤一个字段

小写嵌套特定键的震动转换

在 PostgreSQL 中 Select 分层 JSON 作为表

转义 Haskell 记录的字段

如何使用 gson 调用默认反序列化

将文件发送到 Rails JSON API

Gson 将一组数据对象转换为 json - Android

春天:返回@ResponseBodyResponseEntity>