如何在Laravel中使用ReactJS渲染foreach

时间:2017-10-25 14:46:10

标签: laravel reactjs

我喜欢做多个Axios响应。我在componentDidMount()

中有以下代码
var self = this;
    axios.get('http://reactlaravel.dev/container/count').then(function (response) {

        for (var container in response.data) {
            var d = response.data[container];

            self.setState({
                name: d.name,
                total: d.total,
                current: d.current
            })
        }
    })

在我渲染类的第二个文件中,我想要显示的不是单个返回,而是从循环返回。我怎样才能做到这一点?

return (
        <div className="container">
            <h1>We hebben nog <strong>{this.props.current}</strong> {this.props.name} zeecontainers over.</h1>

            <div className="progress">
                <div className={progressBarType} role="progressbar" aria-valuenow={progressBar} aria-valuemin="0" aria-valuemax="100" style={style}>
                    <span className="sr-only">{progressBar}% Complete (success)</span>
                </div>
            </div>
        </div>
    );

1 个答案:

答案 0 :(得分:1)

您应该将容器设为子组件,并将数据提取保留在父组件中。然后,一旦收到数据,请执行foreach并将容器数据作为道具传递给它。

&#13;
&#13;
const containers = [{name: 'Test', total: 95, current: 45},{name: 'Test 2', total: 95, current: 85},{name: 'Test 3', total: 25, current: 25}]

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      containers: []
    };
  }
  componentDidMount() {
    var self = this;
    //axios.get('http://reactlaravel.dev/container/count').then((response) => {
      
      // Mocking data call here
      this.setState({
        containers: containers //response.data
      });

          
      //})
  }
  render() {
    const containers = this.state.containers.map( (container, i) => <Container key={i} {...container} /> );

    return (
      <div>
        {containers}
      </div>
    )
  }
}

const Container = ({ name, total, current }) => (
  <div>
    <span>{name}</span>
    <span>{total}</span>
    <span>{current}</span>
  </div>
);

ReactDOM.render(<Parent />, document.getElementById('root'));
&#13;
<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>
&#13;
&#13;
&#13;