为什么history.goBack()在reactjs中渲染TWICE

时间:2020-06-10 15:26:39

标签: reactjs react-redux react-router react-navigation react-props

我正在尝试制作一个具有搜索页面的Web应用程序。现在,我在标题上有一个搜索栏,单击它会将用户重定向到“ / search”上的搜索页面。

在搜索页面中,我有一个后退按钮,单击该按钮可使用react-router的“ history.goBack”道具。

但是,问题是每当我单击“后退”按钮时,都会两次(在Search.js中)看到控制台日志。

Search.js | { show:true..... }
Search.js | { show:false.... }

即使有人单击“后退”按钮,为什么它还是第一次显示真实。它会触发Search.js中的“ backClickHandler()”,从而将show切换为false。

当我用'history.push(“ /”)'替换history.goBack时,重定向时根本不显示任何控制台。

这是否意味着我的组件被渲染两次,如何解决?

// app.js

const Search = lazy(() => import("./container/Search/Search"));

class App extends Component {
  render() {
    let layout = <Layout {...this.props} />;
    if (this.props.show || this.props.location.pathname === "/search") {
      layout = null;
    }

    return (
      <div className="App">
        <ErrorBoundary>
          {layout}
          <Route
            path="/search"
            exact
            render={() => (
              <Suspense fallback={<Spinner />}>
                <Search />
              </Suspense>
            )}
          />
        </ErrorBoundary>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    show: state.search.show,
  };
};

export default connect(mapStateToProps, null)(withRouter(App))

// Search.js

    class Search extends Component {
  state = {
    inputValue: "",
  };

  inputChangedHandler = (event) => {
    const newValue = event.target.value;
    this.setState({ inputValue: newValue });
  };

  backClickHandler = () => {
    this.props.onCancelSearch();
    this.props.history.goBack();
  };

  render() {


    console.log("Search.js | ", this.props); //this log


    return (
      <SearchPage
        searchNow={() => {}}
        back={this.backClickHandler}
        changed={this.inputChangedHandler}
        searchValue={this.state.inputValue}
      />
    );
  }
}

const mapStateToProps = (state) => {
  return {
    show: state.search.show,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onCancelSearch: () => dispatch(actions.cancelSearch()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Search));

/store/reducer/search.js

    const initialState = {
  show: false,
  error: null,
  loading: false,
};

const startSearch = (state, action) => {
  return updateObject(state, { show: true });
};

const cancelSearch = (state, action) => {
  return updateObject(state, { show: false });
};

const failSearch = (state, action) => {
  return state;
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.SEARCH_START:
      return startSearch(state, action);
    case actionTypes.SEARCH_CANCEL:
      return cancelSearch(state, action);
    case actionTypes.SEARCH_FAIL:
      return failSearch(state, action);
    default:
      return state;
  }
};

export default reducer

;

0 个答案:

没有答案