zoukankan      html  css  js  c++  java
  • [React] Use the URL as the source of truth in React

    In Single Page Apps we're used to fetch the data on event callbacks. That disables the capacity to use the URL to share it to someone else and get to the same state of the app, just like in non Single Page Apps.

    This lesson shows you how to use React and React Router to use the URL as the source of truth for your app state.

    Doing this in React, we can devide into three steps:

    1. We can use 'withRouter' HOC to get 'location' props.

    2. Handle refresh case: when page refresh, we want to check whether there is query string, if yes, then we need to fetch the data from the BE.

    3, Hnadle query string changes case: when the query string changes, we want to use 'componentWIllReceiveProps' lifecycle to get udpated query string, then fetch the data from BE.

    import React from "react";
    import { render } from "react-dom";
    import { withRouter } from "react-router";
    import { HashRouter, Route, Switch } from 'react-router-dom';
    import Search from "./Search";
    
    const styles = {
      fontFamily: "sans-serif",
      textAlign: "center"
    };
    
    // Step 1
    const App = withRouter(() => (
      <div style={styles}>
        <Switch>
          <Route exact path="/" component={Search} />
        </Switch>
      </div>
    ));
    
    render(
      <HashRouter>
        <App />
      </HashRouter>,
      document.getElementById("root")
    );
    
    
    -----------------------
    
    
    import React, { Component } from "react";
    
    const baseUrl = "https://jsonplaceholder.typicode.com/posts";
    
    class Hello extends Component {
      state = {
        results: []
      };
    
      // Step 2
      componentDidMount() {
        const queryString = this.props.location.search;
    
        if (queryString) {
          this.fetch(queryString);
        }
      }
    
      // Step 3
      componentWillReceiveProps({ location }) {
        const oldQueryString = this.props.location.search;
        const queryString = location.search;
    
        if (oldQueryString !== queryString) {
          this.fetch(queryString);
        }
      }
    
      fetch = (queryString = "") => {
        fetch(`${baseUrl}${queryString}`)
          .then(res => res.json())
          .then(results => this.setState({ results }));
      };
    
      handleChange = ev => {
        const { value } = this.input;
        const queryString = value ? `?q=${value}` : "";
        const currentUrl = window.location.href.split("?")[0];
        window.location = `${currentUrl}${queryString}`;
      };
    
      render() {
        return (
          <div>
            <input ref={input => (this.input = input)} onBlur={this.handleChange} />
            <br />
            {this.state.results.map((res, i) => <p key={i}>{res.title}</p>)}
          </div>
        );
      }
    }
    
    export default Hello;
  • 相关阅读:
    Java实现 N的阶乘
    Java实现 N的阶乘
    Java实现 N的阶乘
    Java实现 N的阶乘
    Java实现 洛谷 P1015 回文数(N进制回文数)
    Java实现 洛谷 P1015 回文数(N进制回文数)
    Java实现 洛谷 P1015 回文数(N进制回文数)
    Java实现 洛谷 P1015 回文数(N进制回文数)
    Java实现 洛谷 P1015 回文数(N进制回文数)
    Windows线程生灭(图文并茂)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7794432.html
Copyright © 2011-2022 走看看