reactjs - React redux 将 this.props 传递给组件中的操作

标签 reactjs react-router redux

在我的组件类中,我有 this.props ,其中包含 history 对象,其中包含 transitionTo 函数。

render() {
    console.log(this.props)

    return (
      <div>
        <button onClick={actions.myAction}>My button</button>
      </div>

这里我的按钮正在调用myAction,它在完成后想要路由到其他位置。我想在我的 action 中访问这个 transitionTo 函数并执行类似 router.transitionTo("/page1")

的操作

为此,我应该获取包含 transitionTo 函数的 history 对象。那么如何将 this.props.history 对象传递给操作。当我执行 onClick={actions.myAction(this.props.history)} 时,我的按钮没有被渲染..

任何帮助

最佳答案

上面的答案是正确的,但在迁移到 "Stateless Components" 时就会崩溃。这很快就会崩溃。我的建议是使用高阶函数来处理防止默认单击操作和提供正确参数的处理。如果您已经在使用 ES2015(例如通过 Babel),这可能很简单:

const preventDefault = (fn, ...args) => (e) => {
  e.preventDefault();
  fn(...args);
};

然后在你的组件中像这样调用:

const Item = ({
  item,
  openItem
}) => (
  <div>
    <h1>{item.title}</h1>
    <a href="#" onClick={preventDefault(openItem, item)}>Open Item</a> // on click will call `openItem(item)`.
  </div>
)

关于reactjs - React redux 将 this.props 传递给组件中的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149207/

相关文章:

reactjs - 在React Route中使用绝对路径或相对路径

reactjs - React 路由器导航栏示例

react-native - Apollo 客户端延迟授权 header

在 react 路由器中找不到嵌套路由的字体

javascript - 如何不使用 Redux 传递 props?

reactjs - "Cannot read property ' getState ' of undefined"创建 redux 模拟存储时

javascript - ERROR : Maximum update depth exceeded. 当组件重复调用时可能会发生这种情况

javascript - 使用react-loadable进行代码分割给出错误: Cannot find module "."

reactjs - Webpack 命令似乎无法在 Windows CLI 上运行

reactjs - 何时在带有 React 的 Typescript 中使用私有(private)/ protected 方法