sahar sahar - 2 months ago 8
React JSX Question

using ajax in react component render

I have a list of contents link, when user clicks item, an ajax request is sent to server and received data should be shown in a react component. I used

componentWillReceiveProps
to send my requests, but refresh the url doesn't work (Router doesn't call component).

it's index.js file:

render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/content/:id" component={UmContent} />
</Route>
</Router>
), document.getElementById('root'));


it's App.js file's "render" function:

render() {
return (
<div>
<h1>App</h1>
<ul>{this.renderItems()}</ul>
{this.props.children}
</div>
);
}


and it's UmContent.js file:

export default class UmContent extends Component {
state = {
data: ''
}

componentWillReceiveProps(props) {

if (!props || !props.params || !props.params.id) {
return;
}
console.log(props.params.id);
let itemId = props.params.id;
let that = this;
$.ajax({
url: "http://192.168.78.2:8585/Default/mygetcontenttoactionresult/" + itemId,
type: 'GET',
dataType: 'html'
}).done((data)=> {
that.setState({data: data});
}).fail(()=> {
that.setState({data: <div> Something is wrong</div>});
});
}

render() {
return (
<div ref="aaa">
<UmC content={this.state.data}/>
</div>);
}
}

Answer

It seems you did something wrong. I rewrite your code for myself.

ContentWrapper to wrap Content component:

import React, {Component, PropTypes} from 'react';
import Content from './content';

class ContentWrapper extends Component {
  state = {
    params: '/something',
  }

  componentWillMount() {
    // Simulate react-router property changing
    setTimeout(() => {this.setState({params: '/something-else'})})
  }

  render() {
    return(
      <Content params={this.state.params} />
    )
  }
}

module.exports = ContentWrapper;

Content component:

import React, {Component, PropTypes} from 'react';
var $ = require("jquery");

class Content extends Component {
  state = {
    text: 'Pending...'
  }

  componentWillReceiveProps(nextProps) {
    $.ajax({
      url: "http://192.168.78.2:8585/Default/mygetcontenttoactionresult/item",
      type: 'GET',
      dataType: 'json'
    }).done((data)=> {
      this.setState({text: 'Success'});
    }).fail(()=> {
      this.setState({text: 'Fail'});
    });
  }

  render() {
    return(
      <span>
        {this.state.text}
      </span>
    )
  }
}

module.exports = Content;

This works for me. Are you sure componentWillReceiveProps is called when route is changed?

Comments