将数据传递给两个组件,但一个渲染失败

时间:2017-12-31 03:51:47

标签: javascript reactjs web

我使用react来制作一个子菜单。父组件获取json,将json传递给另外两个子组件。但是唯一的子项成功显示,另一个子组件失败。两个孩子共享了孙子组件。

class SubMenu extends React.Component {
  render() {
    var submenulink = require("../../../conf/navigation.json")

  return (
    <div>
       <PoliticsSubMenu politics_link={submenulink.politics}/>
       <LawSubMenu law_link={submenulink.law}/>
    </div>
)}}


class PoliticsSubMenu extends React.Component {
  render() {
    return (
      <SubMenuList link={this.props.politics_link} />
)}}

class LawSubMenu extends React.Component {
  render() {
    console.log(this.props.law_link)
    return (
      <SubMenuList link={this.props.law_link}/>
    )
  }
}
class SubMenuList extends React.Component {

  render() {
    const links = this.props.link;
    const listNames = links.map((item) =>
      <li>{item.description}</li>
    )

    return (
      <li className="active">
          <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false">politics</a>
          <ul className="collapse list-unstyled" id="homeSubmenu">
              <li>{listNames}</li>
          </ul>
      </li>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

我对你的&#34; submenulink&#34;进行了硬编码。您的示例代码周围的对象及其在此沙箱中的呈现:https://codesandbox.io/s/pmx95r935m。你的&#34; navigation.json&#34;文件看起来像?

class SubMenu extends React.Component {
  render() {
    var submenulink = {
      politics: [{ description: "First" }, { description: "Second" }],
      law: [{ description: "Premiero" }, { description: "Segundo" }]
    };

    return (
      <div>
        <PoliticsSubMenu politics_link={submenulink.politics} />
        <LawSubMenu law_link={submenulink.law} />
      </div>
    );
  }
}

其他想法:

  1. SubMenuList组件在<li>周围不应该有{listNames}标记。每个listName项都有一个<li>
  2. SubMenuList有一个listNames列表。列表应包含密钥。即:links.map((item, i) => <li key={i}>{item.description}</li>)&#34;键帮助React识别哪些项目已更改,已添加或已删除。应该给出数组内部元素的键,以使元素具有稳定的标识。来自https://reactjs.org/docs/lists-and-keys.html
  3. 没有状态的组件的简单语法(AKA:&#34; dumb&#34;组件)可以使组件定义简洁。

    const PoliticsSubMenu = (props) => <SubMenuList link={props.politics_link} />;