如何在React中获取更新的数据

时间:2018-10-31 11:17:49

标签: reactjs

如何通过调用将由ajax从另一页面接收的新数据来获取更新的react数据?

如何将新数据替换为“结果”分区。

class App extends React.Component {
  constructor(props){
    super(props);
      this.state = {
        data: [],
        }  
    $.ajax({
      url:"/test.bc",
      type:"get",
      success:(result)=>{
        this.setState({data: eval(result)});
      }
    })
    $(document).on('update_result',(event,startairline,classname,stops)=>{
      $.ajax({
        url:"/new.bc",
        type:"post",
        data:{
          startairline:startairline,
          stops:stops,
          classname:classname,
        },
        success:(result)=>{
          console.log(result)
          this.setState({hasBeenChanged: true,data:eval(result)})
        },
      })
    });
  }

  renderFlight(){
    return this.state.data.map((item)=>{ 
      return(<input type="hidden" value={item.total} name="total" /> )
    } )}

  render(){  
    return(<div>{this.renderFlight()}</div>  )
  }
}

ReactDOM.render(<App/>, document.getElementById('Result')); 

1 个答案:

答案 0 :(得分:1)

我为您准备了一个示例,使用 componentDidMount fetch

Here working

    let { Table } = ReactBootstrap;

    class Example extends React.Component {
        constructor(props, context) {
        super(props, context);

        this.state = {
            products: []
        }
        }

        componentDidMount() {
        console.log('componentDidMount..')
        fetch('https://api.github.com/users/xiaotian/repos')
            .then(response => response.json())
            .then(output => {
            let products = []
            for (let i = 0; i < output.length; i++) {
                products.push({selected:false,name:output[i].name})
            }

            this.setState({products},() => console.log(this.state))

        })

        }

        render() {

            return(<Table striped bordered condensed hover>
                <thead>
                <tr>
                    <th>Selected</th>
                    <th>Name</th>
                </tr>
                </thead>
                <tbody>
                {this.state.products.map((item, i) => {
                    return (
                        <tr><td><input type="checkbox" checked={item.selected}/></td><td>{item.name}</td></tr>
                    ) 
                })}
                </tbody>
            </Table>)
        }
    }

    ReactDOM.render(
        <Example />, 
        document.getElementById('app')
    );