反应路由器 | 如何重置为初始状态

Nul*_*rue 5 javascript ecmascript-6 reactjs react-router

你能帮我理解正确的修复是 React Router 还是 React 相关的吗?

我希望能够在每次用户再次访问同一条路线时重置状态(不确定这是否是正确的术语)。

我有一个原型可以检查给定汽车的正确颜色正确成本

正如您将在下面看到的,我的问题是每次我都使用相同的路线和/或我的随机播放方法。我的控制显示/隐藏颜色状态的列表不会自行重置。

我有单独的路由渲染<Cost/><Color/>组件

export const Routes = ({ state, shuffle }) => (
  <Switch>
    <Route
      path="/car-cost"
      render={() => <Cost {...state} shuffle={shuffle} />}
    />
    <Route
      path="/car-color"
      render={() => <Color {...state} shuffle={shuffle} />}
    />
  </Switch>
);
Run Code Online (Sandbox Code Playgroud)

然后我将路由传递到我的主要父组件中。IE:

// MAIN PARENT COMPONENT
export default class Dealership extends Component {
  state = {
    cars: [
      { name: "Ferrari", cost: "$9.000", color: "red", id: 1 },
      { name: "Porsche", cost: "$8.000", color: "black", id: 2 },
      { name: "lamborghini", cost: "$7.000", color: "green", id: 3 },
      { name: "McLaren", cost: "$6.000", color: "silver", id: 4 },
      { name: "Corolla", cost: "$50", color: "brown", id: 5 },
      { name: "Prius", cost: "$40", color: "beige", id: 6 },
      { name: "Saab", cost: "$30", color: "navy blue", id: 7 }
    ]
  };

  handleShuffle = () => {
    this.setState({
      cars: [...this.state.cars.sort(() => Math.random() - 0.5)]
    });
  };

  render() {
    return (
      <BrowserRouter>
        <div>
          <Navigation />
          <Routes
            state={this.state}
            shuffle={this.handleShuffle}
          />
        </div>
      </BrowserRouter>
    );
  }
}


Run Code Online (Sandbox Code Playgroud)

下面的示例显示了该<Cost />组件:

// QUESTION COMPONENT
const Question = ({ guess }) => <h1>What car is {guess}</h1>;

// COST COMPONENT
export default class Cost extends Component {
  render() {
    const { cars, shuffle } = this.props;
    const correctIndex = Math.floor(Math.random() * (cars.length - 1));
    const correctCar = cars[correctIndex];

    const car = cars.map(car => (
      <CarList
        key={car.id}
        name={car.name}
        guess={car.cost}
        isCorrect={correctCar.cost === car.cost}
        greet={this.onGreet}
      />
    ));

    return (
      <>
        <Question key={correctCar.id} guess={correctCar.cost} />
        <button onClick={shuffle}>go again</button>
        <ul className="car-list">{car}</ul>
      </>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上,上面的组件接收一个列表,如果汽车的成本与组件上询问的成本相匹配,则该列表<CarList/>控制状态以显示和显示颜色<Question />

export const Routes = ({ state, shuffle }) => (
  <Switch>
    <Route
      path="/car-cost"
      render={() => <Cost {...state} shuffle={shuffle} />}
    />
    <Route
      path="/car-color"
      render={() => <Color {...state} shuffle={shuffle} />}
    />
  </Switch>
);
Run Code Online (Sandbox Code Playgroud)

我正在处理用于显示和控制<Carlist/>组件内部颜色的状态,以便每个组件都<li/>可以侦听单击事件并做出相应的行为。

您也可以在此 [代码沙箱][1] 上看到的问题是,每次我遇到相同的路线或handleShufle()方法时,都会相应地进行随机化,但<CarList/>状态保持不变。

单击同一链接路由时,如何将其重置回原始状态?