React.js history.push 在单独的函数中?

React.js history.push in a separate function?

你能帮我实现 React.js history.push 功能吗?

我有一个可以按下的图标。 onClick 调用 handleRemoveFavourite 函数,该函数从 localStrorage 中过滤掉当前项目并将更新后的字符串设置为存储。这很好用。

存储更新完成后,程序应将用户重新路由到根页面/favourites。重新路由在底部示例中运行良好。但是如何在 handleRemoveFavourites 函数中做到这一点呢?

这是我想要的代码

handleRemoveFavourite = () => {
    const { name } = this.props.workout;
    let savedStorage = localStorage.saved.split(",");
    let cleanedStorage = savedStorage.filter(function(e) {
      return e !== name;
    });
    localStorage.setItem("saved", cleanedStorage.toString());
    history.push("/favourites")
  };

  renderHeartIcon = () => {
    return (
      <Route
        render={({ history }) => (
          <Rating
            icon="heart"
            defaultRating={1}
            maxRating={1}
            onClick={this.handleRemoveFavourite}
          />
        )}
      />
    );
  };

重新路由可以正常工作:

  renderHeartIcon = () => {
    return (
      <Route
        render={({ history }) => (
          <Rating
            key={1}
            icon="heart"
            defaultRating={1}
            maxRating={1}
            size="large"
            onClick={() => history.push("/favourites")}
          />
        )}
      />
    );
  };

整个组件如下所示:

import React from "react";
import {
  Container,
  Grid,
  Icon,
  Label,
  Table,
  Header,
  Rating,
  Segment
} from "semantic-ui-react";
import { Link, Route } from "react-router-dom";

export default class WorkoutComponent extends React.PureComponent {
  renderChallengeRow = workouts => {
    let { reps } = this.props.workout;
    reps = reps.split(",");

    return workouts.map((item, i) => {
      return (
        <Table.Row key={item.id}>
          <Table.Cell width={9}>{item.name}</Table.Cell>
          <Table.Cell width={7}>{reps[i]}</Table.Cell>
        </Table.Row>
      );
    });
  };

  handleRemoveFavourite = () => {
    const { name } = this.props.workout;
    let savedStorage = localStorage.saved.split(",");
    let cleanedStorage = savedStorage.filter(function(e) {
      return e !== name;
    });
    localStorage.setItem("saved", cleanedStorage.toString());
    // history.push("/favourites");
  };

  renderHeartIcon = () => {
    return (
      <Route
        render={({ history }) => (
          <Rating
            key={1}
            icon="heart"
            defaultRating={1}
            maxRating={1}
            size="large"
            onClick={this.handleRemoveFavourite}
          />
        )}
      />
    );
  };

  render() {
    const { name, workouts } = this.props.workout;
    const url = `/savedworkout/${name}`;
    return (
      <Grid.Column>
        <Segment color="teal">
          <Link to={url}>
            <Header as="h2" to={url} content="The workout" textAlign="center" />
          </Link>
          <Table color="teal" inverted unstackable compact columns={2}>
            <Table.Body>{this.renderChallengeRow(workouts)}</Table.Body>
          </Table>
          <br />
          <Container textAlign="center">
            <Label attached="bottom">{this.renderHeartIcon()}</Label>
          </Container>
        </Segment>
        <Link to="/generate">
          <Icon name="angle double left" circular inverted size="large" />
        </Link>
      </Grid.Column>
    );
  }
}

更改为 this.props.history.push("/favourites"); 应该可以。

已编辑

您的组件是否在路由内?如果是这样,this.props.history 将起作用。我测试了在我的项目中将您的 class 更改为 运行。

import React from 'react';
import ReactDOM from 'react-dom';
import {
  Container,
  Grid,
  Icon,
  Label,
  Table,
  Header,
  Rating,
  Segment
} from "semantic-ui-react";
 import { Link, Route, BrowserRouter  as Router } from "react-router-dom";

export default class WorkoutComponent extends React.Component {
  static defaultProps = {
      workout: {
          reps: "1,2,3,4",
          workouts: []
      },

  }
  renderChallengeRow = workouts => {
    let { reps } = this.props.workout;
    reps = reps.split(",");

    return workouts.map((item, i) => {
      return (
        <Table.Row key={item.id}>
          <Table.Cell width={9}>{item.name}</Table.Cell>
          <Table.Cell width={7}>{reps[i]}</Table.Cell>
        </Table.Row>
      );
    });
  };

  handleRemoveFavourite = () => {
    const { name } = this.props.workout;
    //let savedStorage = localStorage.saved.split(",");
    // let cleanedStorage = savedStorage.filter(function(e) {
    //   return e !== name;
    // });
    // localStorage.setItem("saved", cleanedStorage.toString());
    this.props.history.push("/favourites");
  };

  renderHeartIcon = () => {
    return (
      <Route
        render={({ history }) => (
          <Rating
            key={1}
            icon="heart"
            defaultRating={1}
            maxRating={1}
            size="large"
            onClick={this.handleRemoveFavourite}
          />
        )}
      />
    );
  };

  render() {
      console.log(this.props)
    const { name, workouts } = this.props.workout;
    const url = `/savedworkout/${name}`;
    return (

          <Grid.Column>
        <Segment color="teal">
          <Link to={url}>
            <Header as="h2" to={url} content="The workout" textAlign="center" />
          </Link>
          <Table color="teal" inverted unstackable compact columns={2}>
            <Table.Body>{this.renderChallengeRow(workouts)}</Table.Body>
          </Table>
          <br />
          <Container textAlign="center">
            <Label attached="bottom">{this.renderHeartIcon()}</Label>
          </Container>
        </Segment>
        <Link to="/generate">
          <Icon name="angle double left" circular inverted size="large" />
        </Link>
      </Grid.Column>
    );
  }
}
ReactDOM.render(
<Router>        
    <Route path="/" component={ WorkoutComponent }/>
</Router>, document.getElementById('root'));
onClick={this.handleRemoveFavourite}
=> 
onClick={()=>this.handleRemoveFavourite(history)}

handleRemoveFavourite = () => {
=>
handleRemoveFavourite = (history) => {

由于您使用的是 react-router,因此您可以使用 withRouter 来实现。

import { withRouter } from 'react-router-dom'

将 class 名称用 withRouter 包裹起来。

像这样:

而不是这样做:

export default class App .....

像这样分开:

class App ...

行尾:

export default withRouter(App)

现在你可以这样使用了:

handleRemoveFavourite = () => {
  const { name } = this.props.workout;
  let savedStorage = localStorage.saved.split(",");
  let cleanedStorage = savedStorage.filter(function(e) {
    return e !== name;
  });
  localStorage.setItem("saved", cleanedStorage.toString());
  this.props.history.push("/favourites");
};

您可以从 renderHearIcon() 中删除 Route:

renderHeartIcon = () => {
    return (
        <Rating
          key={1}
          icon="heart"
          defaultRating={1}
          maxRating={1}
          size="large"
          onClick={this.handleRemoveFavourite}
        />
    );
  };

您面临的问题是,您正在为 <Route> 提供 history 道具,以便它在组件函数调用中传播。但是您没有将它传播到 handleRemoveFavourite 函数。

您需要将 this. handleRemoveFavourite 包裹在匿名函数调用中。喜欢

          onClick={() => this.handleRemoveFavourite(history)}

然后接受它作为函数中的有效参数

handleRemoveFavourite = (history) => {...}

应该可以解决