高阶组件和反应的APi

时间:2018-03-05 04:12:56

标签: reactjs

我是React.js的新手。有一个高阶组件的问题。如下所示,如果我用 RandomMeUsers count = {10} 更改render()。如何修改 const RandomMeUsers = DataComponent(...)以接收 count = {10} 来操纵我请求的号码?

  <script type="text/babel">

    const { Component } = React
    const { render } = ReactDOM

    const DataComponent = (ComposedComponent, url) =>
      class DataComponent extends Component {

          constructor(props) {
              super(props)
              this.state = {
                  data: [],
                  loading: false,
                  loaded: false
              }
          }

          componentWillMount() {
              this.setState({loading:true})
              fetch(url)
                  .then(response => response.json())
                  .then(data => this.setState({
                      loaded: true,
                      loading: false,
                      data
                  }))
          }

          render() {
              return (
                  <div className="data-component">
                      {(this.state.loading) ?
                          <div>Loading...</div> :
                          <ComposedComponent {...this.state}
                                             {...this.props} />}
                  </div>
              )
          }
      }

    const PeopleList = ({data}) =>
      <ol className="people-list">
          {data.results.map((person, i) => {
              const {first, last} = person.name
              return <li key={i}>{first} {last}</li>
          })}
      </ol>

    const RandomMeUsers = DataComponent(
                            PeopleList,
                            "https://randomuser.me/api?results=10"
                        )

    render(
      <RandomMeUsers />,
      document.getElementById('react-container')
    )


  </script>

1 个答案:

答案 0 :(得分:0)

你无法收到像这样的其他道具

const PeopleList = ({data, count, loading, etc}) => (
  <ol className="people-list">
    {data.results.map((person, i) => {
      const {first, last} = person.name
        return <li key={i}>{first} {last}</li>
    })}
  </ol>
)