如何在React JS上通过Ajax发布新数据

时间:2016-11-01 23:38:23

标签: javascript ajax reactjs asynchronous http-post

考虑这个example

我在React真的很新,所以这就是我创建新应用的方式

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = { //initial empty details
      details : {}
    }
  }
  componentDidMount(){
    //place the ajax call where ever you need
    $.ajax() //call ajax
    .done((data) => {
      this.setState({ //this setState will re render the UI with the new state
        details: { //change the key value pairs as needed
          id: data.id,
          trackInfo: {
            title: data.title,
            artist: data.artist,
            album: data.album,
          },
          trackUrl: data.trackUrl,
          albumArt: data.albumArt,
        }
      })
    })
  }
    render() {
      if(!this.state.details.id) return false //renders nothing when no details available
        return (
            <div id="app">
                <MusicPlayer
                    id={this.state.details.id}
                    visualizerType="RIPPLES"
                    theme={darkTheme}
                    trackInfo={this.state.details.trackInfo}
                    trackUrl={this.state.details.trackUrl}
                    albumArt={this.state.details.albumArt}
                    utilities={true}>
                </MusicPlayer>
            </div>
        )
    }
}

ReactDOM.render(
    <App />,
    document.getElementById("app")
);

计划是创建一个按钮,点击它时会显示一个新的MusicPlayer元素。例如

<MusicPlayer
    id="3"
    visualizerType="RIPPLES"
    theme={lightTheme}
    trackInfo={{
        title: "Guns & Dogs",
            artist: "Portugal, The Man",
                album: "The Satanic Satanist"
    }}
    trackUrl="https://s3-us-west-2.amazonaws.com/teddarcuri.monarch/Portugal.+The+Man+-+Guns+%26+Dogs+-+The+Satanic+Satanist.mp3"
    albumArt="http://ecx.images-amazon.com/images/I/61X7CiBpZ6L.jpg"
    utilities={true}>
</MusicPlayer>

如何通过Ajax将新的JSON数据正确地发布到渲染?

1 个答案:

答案 0 :(得分:2)

假设您的原始ES6 / JSX看起来像这样:

class App extends React.Component {
    constructor() {
        super();

        this.state = {
            details: {},
        };
    }

    componentDidMount() {
        $.ajax() // call ajax
        .done(data => {
            this.setState({ // this setState will re render the UI with the new state
                details: { // change the key value pairs as needed
                    id: data.id,
                    trackInfo: {
                        title: data.title,
                        artist: data.artist,
                        album: data.album,
                    },
                    trackUrl: data.trackUrl,
                    albumArt: data.albumArt,
                },
            });
        });
    }

    render() {
        return (
            <div>
                <MusicPlayer
                  {...{
                      id: this.state.details.id,
                      visualizerType: 'RIPPLES',
                      theme: darkTheme,
                      trackInfo: this.state.details.trackInfo,
                      trackUrl: this.state.details.trackUrl,
                      albumArt: this.state.details.albumArt,
                      utilities: true,
                  }}
                />
            </div>
        );
    }
}

并且您希望再次针对按钮点击的某些新玩家数据进行$ .ajax调用。您需要为可以更新组件状态的单击处理程序创建一个方法。这看起来像是:

class App extends React.Component {
    constructor() {
        super();

        this.state = {
            details: {},
        };

        // this is important so that the getNewData method will have the correct "this" context on click
        this.getNewData = this.getNewData.bind(this);
    }

    componentDidMount() {
        $.ajax() // call ajax
        .done(data => {
            this.setState({ // this setState will re render the UI with the new state
                details: { // change the key value pairs as needed
                    id: data.id,
                    trackInfo: {
                        title: data.title,
                        artist: data.artist,
                        album: data.album,
                    },
                    trackUrl: data.trackUrl,
                    albumArt: data.albumArt,
                },
            });
        });
    }

    getNewData(e) {
        e.preventDefault();

        // any logic to set up url or params for the ajax call can be done here

        $.ajax() // call ajax
        .done(data => {
            this.setState({ // this setState will re render the UI with the new state
                details: { // change the key value pairs as needed
                    id: data.id,
                    trackInfo: {
                        title: data.title,
                        artist: data.artist,
                        album: data.album,
                    },
                    trackUrl: data.trackUrl,
                    albumArt: data.albumArt,
                },
            });
        });
    }

    render() {
        return (
            <div>
                <MusicPlayer
                  {...{
                      id: this.state.details.id,
                      visualizerType: 'RIPPLES',
                      theme: darkTheme,
                      trackInfo: this.state.details.trackInfo,
                      trackUrl: this.state.details.trackUrl,
                      albumArt: this.state.details.albumArt,
                      utilities: true,
                  }}
                />

                <button onClick={this.getNewData}>Click me!</button>
            </div>
        );
    }
}

这是实现目标的简单方法,但数据已本地化为此组件。如果您有一个复杂的应用程序,您可能希望使用Redux和异步操作或中间件执行此操作,但这需要更复杂的应用程序设置。