如何使用 Reactjs 将日历的日期状态发送到另一个日历?

IT技术 javascript reactjs state react-props react-big-calendar
2021-05-16 01:45:06

我有两个日历,比如 Agenda,有一个图标日历按钮,当我点击它时,它会被重定向到另一个日历(Planning),这些日历是用react-big-calendar 开发的,我想当我导航时一周的juin 17 - 23议程,我点击图标日历,它将被重定向到juin 17 - 23计划。

我的代码是:https : //codesandbox.io/s/m7k904y3o8

我尝试用 发送日期getWeek(),但它不起作用。

我该如何解决?

2个回答

您可以添加额外的数据this.props.history.push,然后这些数据location在您的Planning组件prop 中可用例如,如果您想查看 1995 年 12 月 20 日的那一周:

// Agenda.js: Routing to "/planning"

this.props.history.push("/planning", { date: new Date(1994, 11, 19, 0, 0)})
// Planning.js

constructor(props) {
    super(props); //Important

    this.state({
        /* ... */
        dateWeek: this.props.location.state && this.props.location.state.date
    });
}

// Following is a fix or else you would not get next/previous week.

getThisWeek = (dateWeek) => {
    this.setState({ dateWeek });
}


我推荐的另外两个解决方案是URL parametersQuery parameters

你应该使用一些状态管理库

我的第一个建议是使用 Redux,因为该库可以很好地处理这种情况。您想在不相关的组件之间传递一些数据。拥有一个状态对象在这里会很好地为您服务。

第二个(更简单/更快)选项是向父组件(这称为容器)添加一些状态管理。您可以将一些状态传递给每个子项以及可以从子项中触发的 setter 函数。

作为容器的 App 组件示例

import React, { Component } from "react";
import autobind from 'autobind-decorator';
import { Route, Link, Switch, Redirect } from "react-router-dom";
import Agenda from "./Agenda";
import Planning from "./Planning";
class App extends Component {
  state = {selectedDate: Date.now()}

  @autobind
  setActiveDate (dateToSet) {
    this.setState({selectedDat: dateToSet});
  }
  /*---------------------------------------------------- Rendu -----------------------------------------------------------------*/
  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" render={(props) => <Agenda {...props} setActiveDate={setActiveDate} selectedDate={this.state.selectedDate} />} />
          <Route exact path="/planning" render={(props) => <Planning {...props} selectedDate={this.state.selectedDate} />}/>
        </Switch>
      </div>
    );
  }
}

export default App;

一些注意事项

  • 首先,您不希望您的主应用程序组件以这种方式用作容器,因此请制作另一个组件来处理此状态管理
  • autobind装饰器的使用是为了让这更容易编写,如果你愿意,你可以在构造函数中绑定你的函数
  • 此组件仅显示故事的一半,另一半在您的子组件中,您需要从此处读取日期并setActiveDate从子组件(议程)中触发功能

结论

这种方法会比 redux 实现更污染你的组件。但这比完整的 redux 设置要快。试着记住“单一责任原则”