将React-Redux添加到辅助函数

时间:2018-12-06 19:31:03

标签: reactjs redux action

我有一个辅助函数,该函数由React应用程序中的两个组件使用。并且此帮助程序函数调度一组Redux操作。如何将React-Redux连接到此辅助函数,以便它可以调度动作?

我的助手看起来像这样:

export default const helper = () => {
   //dispatch some actions
   // I would like to do something similar to  this: this.props.dispatch()
   //do something else(produce some JSX)
}

我的组件看起来像这样:

 import helper from './helper.js';

 export default class Example extends React.Component {
   return (
      {helper()}
   );
 }

我的组件 1 如下所示:在组件本身内部定义了辅助程序:

 import { setTime } from '../actions/setTime.js';

 class Example1 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (<h1>hello</h1>);
   }

   render() {
     return (
      <h1>something</h1>
      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example1);

我的组件 2 如下所示:在组件本身内部定义了助手:

 import { setTime } from '../actions/setTime.js';

 class Example2 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (<h1>hello</h1>);
   }

   render() {
     return (
      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example2);

Example1和Example2基于Route更改进行渲染。您可能会以为我可以使用高阶组件,但不能,因为这两个组件具有不同的状态并呈现不同的内容。

请注意,我想访问辅助方法中的调度功能,并且不从该组件访问Redux状态,因此我不必担心状态更改(未使用mapStateToProps)。

2 个答案:

答案 0 :(得分:2)

这是XY问题。

react-reduxconnect应该与组件一起使用,它依赖于组件层次结构(React上下文)为组件提供存储。 connect不应该与不属于组件层次结构的函数一起使用。

可以在辅助函数中直接访问store.dispatch,但这表明设计存在问题,因为isn't supposed to be used directly in React的底层API

组件组成是在React中组成功能的惯用方式。 helper函数执行副作用(调度一个动作)并返回一个元素。可以表示为连接的组件:

const Helper = props => {
 props.setTime('10:00PM');

 return (<h1>hello</h1>);
};


 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

export default connect(null, mapDispatchToProps)(Helper);

答案 1 :(得分:1)

我遇到了类似的问题,我通过将this传递给辅助函数来解决它。 如果您需要采取行动将其分派,例如expample可能会有所帮助。

export default const helper = (that) => {
 return <button onClick={()=>that.props.YourDispatch()}/>
}


 import helper from './helper.js';

 export default class Example extends React.Component {
   return (
      {helper(this)}
   );
 }