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

时间:2018-09-13 05:37:28

标签: javascript reactjs react-router-dom

您能帮我使用React.js history.push函数吗?

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

完成存储更新后,程序应将用户重新路由到根目录/收藏夹。在下面的示例中,重新路由效果很好。但是如何在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>
    );
  }
}

4 个答案:

答案 0 :(得分:2)

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

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

用类名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");
};

您可以从Route中删除renderHearIcon()

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

您面临的问题是,您要向string result = str.Split(new char[] {'\r'}, 3)[1]; 提供历史记录道具,以便在组件函数调用中传播它。但是您没有将其传播到<Route>函数。

您需要将handleRemoveFavourite包装在一个匿名函数调用中。像

this. handleRemoveFavourite

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

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

应该解决的

答案 3 :(得分:0)

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

编辑

您的组件是否在路线内?如果是这样,this.props.history将起作用。我测试过更改您的类以在我的项目上运行。

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'));