将数据从功能组件传递到app.js

时间:2018-11-07 11:11:43

标签: reactjs redux

我是React的新手,仍然在学习它的基础知识。 我在students.js中有一个组件:

export const studentslist = () => {
  return [
    {
      name: "aaaa",
      surname: "aaa"
    },
    {
      name: "bbbbb",
      surname: "bbbb"
    },
    {
      name: "ccccc",
      surname: "ccc"
    }
  ];
};

如何将此学生名单传递给我的App.js进入状态并使用它?

1 个答案:

答案 0 :(得分:0)

studentslist不是组件,因为函数仅返回数据数组,但是您要使用函数返回的内容作为组件的初始状态,可以将其导入组件文件并将其分配给状态在构造函数中或在类属性中。

示例

// studentslist.js
export const studentslist = () => {
  return [
    {
      name: "aaaa",
      surname: "aaa"
    },
    {
      name: "bbbbb",
      surname: "bbbb"
    },
    {
      name: "ccccc",
      surname: "ccc"
    }
  ];
};

// App.js
import React from "react";
import studentslist from "./studentslist";

class App extends React.Component {
  state = { studentslist: studentslist() };

  render() {
    return <div>{JSON.stringify(this.state)}</div>;
  }
}

const studentslist = () => {
  return [
    {
      name: "aaaa",
      surname: "aaa"
    },
    {
      name: "bbbbb",
      surname: "bbbb"
    },
    {
      name: "ccccc",
      surname: "ccc"
    }
  ];
};

class App extends React.Component {
  state = { studentslist: studentslist() };

  render() {
    return <div>{JSON.stringify(this.state)}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>