Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - How to fetch the new data in response to React Router change with Redux?

I'm using Redux, redux-router and reactjs.

I'm trying to make an app where I fetch information on route change, so, I've something like:

<Route path="/" component={App}>
    <Route path="artist" component={ArtistApp} />
    <Route path="artist/:artistId" component={ArtistApp} />
</Route>

When someone enters to artist/<artistId> I want to search for the artist and then render the information. The question is, what it's the best way of doing this?

I've found some answers about it, using RxJS or trying a middleware to manage the requests. Now, my question is, Is this really necessary or just a way to keep the architecture react-agnostic? Can I just fetch the information I need from react componentDidMount() and componentDidUpdate() instead? Right now I'm doing this by triggering an action in those functions that request information and the component re-renders when the information has arrived. The component has some properties for letting me know that:

{
    isFetching: true,
    entity : {}
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now, my question is, Is this really necessary or just a way to keep the architecture react-agnostic? Can I just fetch the information I need from react componentDidMount() and componentDidUpdate() instead?

You can totally do that in componentDidMount() and componentWillReceiveProps(nextProps).
This is what we do in real-world example in Redux:

function loadData(props) {
  const { fullName } = props;
  props.loadRepo(fullName, ['description']);
  props.loadStargazers(fullName);
}

class RepoPage extends Component {
  constructor(props) {
    super(props);
    this.renderUser = this.renderUser.bind(this);
    this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
  }

  componentWillMount() {
    loadData(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.fullName !== this.props.fullName) {
      loadData(nextProps);
    }

  /* ... */

}

You can get more sophisticated with Rx, but it's not necessary at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...