代码之家  ›  专栏  ›  技术社区  ›  loveTrumpsHate

向助手函数添加React-Redux

  •  0
  • loveTrumpsHate  · 技术社区  · 7 年前

    我有一个助手功能,在我的React应用程序中有两个组件使用它。这个helper函数分派一组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);
    

    示例1和示例2基于路线更改进行渲染。你可能认为我可以使用高阶组件,但我不能,因为这两个组件有不同的状态,呈现不同的东西。

    请注意,我希望能够访问helper方法中的dispatch函数,并且我没有从该组件访问Redux状态,因此我不必担心状态更改(mapstatetops未使用)。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Estus Flask    7 年前

    react-redux 和 connect 不应与不属于组件层次结构的函数一起使用。

    有可能访问 store.dispatch 直接在helper函数中,但这表明存在设计问题,因为它是低级别API isn't supposed to be used directly in 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);
    
        2
  •  1
  •   marc_s MisterSmith    7 年前

    我有一个类似的问题,我顺便解决了 this 帮助器功能。

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