reactjs - React 数组作为 prop 传递给 SFC 时转换为对象

标签 reactjs

我有一个 react 函数,我正在传递一个对象数组作为 Prop 。当组件渲染时,该数组被嵌套到同名的对象中。

为什么要嵌套?我可以做些什么来将其强制返回数组吗?

这是代码(以及笔的链接( https://codepen.io/bluesixty/pen/PJQKVq?editors=0010 ):

const tags = [
      {
        name: 'ios',
        link: '',
      },
      {
        name: 'ANDROID',
        link: '',
      },
      {
        name: 'REACT',
        link: '',
      },
      {
        name: 'javascript',
        link: '',
      },
    ]


const App = tagList => {

    return (
      <div>
        This is a React component!
        <ul>
          {tagList.tagList.map((tag, i) => (
            <li>
              {tag.name}
            </li>
        ))}
        </ul>
      </div>
    );
  }


ReactDOM.render(
    <App tagList={tags}/>,
  document.getElementById('root')
);

删除 .map 中的第二个 tagList 失败,并显示“tagList.map 不是函数”。这是真的,它现在是一个对象了???

{tagList.map((tag, i) => (

最佳答案

功能组件接收 props 作为第一个参数,因此正确的代码是:

const App = props => {

    return (
      <div>
        This is a React component!
        <ul>
          {props.tagList.map((tag, i) => (
            <li>
              {tag.name}
            </li>
        ))}
        </ul>
      </div>
    );
  }

也可以这样写:

const App = ({ tagList }) => (
  <div>
    This is a React component!
    <ul>
      {tagList.map(({ name }, i) => (
        <li>
          {name}
        </li>
      ))}
    </ul>
  </div>
);

关于reactjs - React 数组作为 prop 传递给 SFC 时转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46612668/

相关文章:

reactjs - React 从嵌套元素中的另一个组件更新组件

javascript - 使用 axios 配置事件设置状态

css - 如何使用 material-ui 和 styled-components 定位按钮库

javascript - react .js : events instead of passing handler in props

reactjs - 无法从 AssyncStorage 检索数据

reactjs - 无法读取未定义的属性 'handleReset'

reactjs - 如何使用它的snake_case名称动态加载图标(React,material-ui)

reactjs - React中如何从子组件获取值

CSS 溢出无法按预期工作并且无法滚动到 div 的底部

Reactjs wordpress 为 SEO 预渲染现有客户端应用程序