问题
I try to interact with data on route changes(I use react-router 1.0.0) but inherited components are not fetching data from API
basically I have my base route which is interacting with the store but the inherited route like /:slug
does not updates the component with new data
it seems like the _onChange
will not fire up!
the component
import React from 'react';
import PropertyStore from '../stores/PropertyStore';
import AppActions from '../actions/AppActions'
class Property extends React.Component{
constructor(){
super();
this.state = {
property: []
}
this._onChange = this._onChange.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentWillMount(){
PropertyStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
PropertyStore.removeChangeListener(this._onChange);
}
componentDidMount () {
AppActions.getProperty( this.props.params.slug );
}
handleChange(e) {}
_onChange() {
this.setState({
property: PropertyStore.getProperty( this.props.params.slug )
});
}
render() {
var property;
if (this.state.property) {
console.log(this.state.property) //empty!!
property = this.state.property.map(function (detail, i) {
return (
<div>{detail.description}</div>)
});
}
return(
<div className="Property"> {property} </div>
)
}
}
module.exports = Property;
AppActions
'use strict';
var AppDispatcher = require('../dispatchers/AppDispatcher');
var AppConstants = require('../constants/AppConstants');
var PropertiesStore = require('../stores/PropertiesStore');
var PropertyStore = require('../stores/PropertyStore');
var Promise = require('es6-promise').Promise; // jshint ignore:line
var Api = require('../services/Api');
var AppActions = {
getProperties: function () {
Api
.get('/api/v2/properties')
.then(function (properties) {
AppDispatcher.handleViewAction({
actionType: AppConstants.RECEIVE_PROPERTIES,
properties: properties.data.properties
});
})
.catch(function () {
AppDispatcher.handleViewAction({
actionType: AppConstants.RECEIVE_ERROR,
error: 'There was a problem getting the workshops'
});
});
},
getProperty: function (slug) {
Api
.get('/api/v2/properties/'+ slug)
.then(function (property) {
AppDispatcher.handleViewAction({
actionType: AppConstants.RECEIVE_PROPERTY,
property: property.data.property
});
})
.catch(function () {
AppDispatcher.handleViewAction({
actionType: AppConstants.RECEIVE_ERROR,
error: 'There was a problem getting the Voucher'
});
});
},
getMedia: function () {
Api
.get('/wp-json/wp/v2/workshops')
.then(function (workshops) {
AppDispatcher.handleViewAction({
actionType: WorkshopConstants.RECEIVE_MEDIA,
workshops: workshops
});
})
.catch(function () {
AppDispatcher.handleViewAction({
actionType: WorkshopConstants.RECEIVE_ERROR,
error: 'There was a problem getting the categories'
});
});
}
};
module.exports = AppActions;
来源:https://stackoverflow.com/questions/34511849/react-router-and-flux-how-to