reactjs - this.props.history.push 不重新渲染 react 组件

标签 reactjs react-router react-router-v4

在我的组件中,我使用 this.props.history.push(pathname:.. search:..) 重新渲染组件并从第三方服务获取新数据。当我第一次调用它呈现的页面时。但是,当我在组件内部调用历史记录推送时,URL 会正确更新,但组件不会重新呈现。我读了很多书,但无法让它发挥作用。有什么想法吗?

我正在使用 React Router v4

//index.js

  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/login" component={Login}/>
        <Route path="/" component={Main}/>
      </Switch>
    </BrowserRouter>
  </Provider>


//Main.js
//PropsRoute is used to push props to logs component so I can use them when fetching new data
const PropsRoute = ({ component: Component, ...rest }) => {
  return (
    <Route {...rest} render={props => <Component {...props} />}/>
  );
};

class Main extends Component {
  render() {
    return (
        <div className="app">
          <NavigationBar/>
          <div className="app-body">
            <SideBar/>
            <Switch>
              <PropsRoute path="/logs" component={Log}/> //this component is not rerendering
              <Route path="/reports" component={Reports}/>
              <Route path="/gen" component={Dashboard}/>
              <Redirect from="/" to="/gen"/>
            </Switch>
          </div>
        </div>
    )
  }
}

export default Main;


//inside 'Log' component I call
import React, {Component} from 'react';
import {getSystemLogs} from "../api";
import {Link} from 'react-router-dom';
import _ from "lodash";
import queryString from 'query-string';

let _isMounted;

class Log extends Component {

  constructor(props) {
    super(props);

    //check if query params are defined. If not re render component with query params
    let queryParams = queryString.parse(props.location.search);
    if (!(queryParams.page && queryParams.type && queryParams.pageSize && queryParams.application)) {
      this.props.history.push({
        pathname: '/logs',
        search: `?page=1&pageSize=25&type=3&application=fdce4427fc9b49e0bbde1f9dc090cfb9`
      });
    }

    this.state = {
      logs: {},
      pageCount: 0,
      application: [
        {
          name: 'internal',
          id: '...'
        }
      ],
      types: [
        {
          name: 'Info',
          id: 3
        }
      ],
      paginationPage: queryParams.page - 1,
      request: {
        page: queryParams.page === undefined ? 1 : queryParams.page,
        type: queryParams.type === undefined ? 3 : queryParams.type,
        pageSize: queryParams.pageSize === undefined ? 25 : queryParams.pageSize,
        application: queryParams.application === undefined ? 'fdce4427fc9b49e0bbde1f9dc090cfb9' : queryParams.application      
      }
    };

    this.onInputChange = this.onInputChange.bind(this);
  }

  componentDidMount() {
    _isMounted = true;
    this.getLogs(this.state.request);
  }

  componentWillUnmount() {
    _isMounted = false;
  }

  getLogs(request) {
    getSystemLogs(request)
      .then((response) => {
        if (_isMounted) {
          this.setState({
            logs: response.data.Data,
            pageCount: (response.data.TotalCount / this.state.request.pageSize)
          });
        }
      });
  }

  applyFilter = () => {
    //reset page to 1 when filter changes
    console.log('apply filter');
    this.setState({
      request: {
        ...this.state.request,
        page: 1
      }
    }, () => {
      this.props.history.push({
      pathname: '/logs',
        search: `?page=${this.state.request.page}&pageSize=${this.state.request.pageSize}&type=${this.state.request.type}&application=${this.state.request.application}`
      });
    });
  };

  onInputChange = () => (event) => {
    const {request} = this.state; //create copy of current object
    request[event.target.name] = event.target.value; //update object
    this.setState({request}); //set object to new object
  };

  render() {
    let logs = _.map(this.state.logs, log => {
      return (
          <div className="bg-white rounded shadow mb-2" key={log.id}>
           ...
          </div>
      );
    });

    return (
      <main className="main">
        ...
      </main>
    );
  }
}

export default Log;

最佳答案

propsstate 发生变化时,Reactjs 不会重新运行 constructor 方法,他会调用 constructor code> 当您第一次调用组件时。

您应该使用componentDidUpdate如果您的 nextProps.location.pathname 与您的 this.props.location.pathname ( react-router location )

不同,则进行提取

关于reactjs - this.props.history.push 不重新渲染 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51417291/

相关文章:

javascript - 如何在服务器端呈现时禁用或阻止 ReactJS 查找文档?

javascript - X-WP-Nonce == Cookie 随机数无效

javascript - div 上 Const 的 ReactJS 值

reactjs - 如何让reactjs/flux/react-router spa同构?

javascript - ReactJS React Router 获取 url 中的更改

reactjs - React Router 中多个可能的精确路径?

javascript - 单击 ReactJs 中表格行中的链接时如何在不同页面中呈现组件

javascript - ReactJS 中的内联样式

reactjs - 在 React-Router v3 中,所有路由都必须嵌套在路径为 ="/"的 <Route> 中吗?

reactjs - 是否可以将非组件类连接到 redux 存储?