32

目标:当加载一个 react-router 路由时,调度一个 Redux action 请求异步Saga worker 为该路由的底层无状态组件获取数据。

问题:无状态组件只是函数,没有生命周期方法,例如 componentDidMount,所以我不能(?)从函数内部调度 Redux 操作。

我的问题部分与将有状态 React 组件转换为无状态功能组件有关:如何实现“componentDidMount”类型的功能?,但我的目标是仅仅调度一个 Redux action 请求异步填充到存储中的数据(我使用 Saga,但我认为这与问题无关,因为我的目标是仅仅调度一个普通的 Redux 动作),之后由于更改了数据属性,无状态组件将重新渲染。

我正在考虑两种方法:要么使用react-router的某些功能,要么使用Redux 的connect方法。是否有所谓的“反应方式”来实现我的目标?

编辑:到目前为止,我想出的唯一解决方案是在 mapDispatchToProps 中调度操作,这种方式:

const mapStateToProps = (state, ownProps) => ({
    data: state.myReducer.data // data rendered by the stateless component
});

const mapDispatchToProps = (dispatch) => {
    // catched by a Saga watcher, and further delivered to a Saga worker that asynchronically fetches data to the store
    dispatch({ type: myActionTypes.DATA_GET_REQUEST });
    return {};
};

export default connect(mapStateToProps, mapDispatchToProps)(MyStatelessComponent);

然而,这似乎有点肮脏而不是正确的方法。

4

5 回答 5

10

我不知道为什么您绝对想要一个无状态组件,而带有 componentDidMount 的有状态组件会以简单的方式完成这项工作。

调度动作mapDispatchToProps是非常危险的,并且可能导致不仅在 mount 上调度,而且在 ownProps 或 store 道具发生变化时调度。在这种应该保持纯净的方法中,预计不会产生副作用。

保持组件无状态的一种简单方法是将其包装到您可以轻松创建的HOC(高阶组件)中:

MyStatelessComponent = withLifecycleDispatch(dispatch => ({
   componentDidMount: function() { dispatch({ type: myActionTypes.DATA_GET_REQUEST })};
}))(MyStatelessComponent)

请注意,如果您在此 HOC 之后使用 Redux connect,您可以轻松地直接从 props 访问 dispatch,就像您不使用mapDispatchToProps, dispatch 一样。

然后你可以做一些非常简单的事情,比如:

let MyStatelessComponent = ...

MyStatelessComponent = withLifecycle({
   componentDidMount: () => this.props.dispatch({ type: myActionTypes.DATA_GET_REQUEST });
})(MyStatelessComponent)

export default connect(state => ({
   date: state.myReducer.data
}))(MyStatelessComponent);

HOC定义:

import { createClass } from 'react';

const withLifeCycle = (spec) => (BaseComponent) => {
  return createClass({
    ...spec,
    render() {
      return BaseComponent();
    }
  })
}

这是您可以执行的操作的简单实现:

const onMount = (onMountFn) => (Component) => React.createClass({
   componentDidMount() {
     onMountFn(this.props);
   },
   render() { 
      return <Component {...this.props} />
   }  
});

let Hello = (props) => (
   <div>Hello {props.name}</div>
)

Hello = onMount((mountProps) => {
   alert("mounting, and props are accessible: name=" + mountProps.name)
})(Hello)

如果您使用connectHello 组件,您可以将 dispatch 作为 props 注入并使用它来代替警报消息。

提琴手

于 2016-09-29T08:46:44.293 回答
5

现在,您可以useEffect像这样使用钩子:

import React, { useEffect } from 'react';
const MyStatelessComponent: React.FC = (props) => {
   useEffect(() => {
      props.dispatchSomeAction();
   });
   return ...
}

这相当于功能/无状态组件的 componentDidMount/componentWillMount生命周期方法。

有关钩子的进一步阅读:https ://reactjs.org/docs/hooks-intro.html

于 2020-02-09T21:15:57.463 回答
4

我想我找到了最干净的解决方案,而无需使用有状态的组件:

const onEnterAction = (store, dispatchAction) => {
    return (nextState, replace) => {
        store.dispatch(dispatchAction());
    };
};

const myDataFetchAction = () => ({ type: DATA_GET_REQUEST });

export const Routes = (store) => (
    <Route path='/' component={MyStatelessComponent} onEnter={onEnterAction(store, myDataFetchAction)}/>
);

该解决方案将存储传递给传递给 onEnter 生命周期方法的更高阶函数。从https://github.com/reactjs/react-router-redux/issues/319找到解决方案

于 2016-09-29T13:06:43.790 回答
1

如果您希望它完全无状态,您可以在使用 onEnter 事件输入路由时分派一个事件。

<Route to='/app' Component={App} onEnter={dispatchAction} />

现在您可以在此处编写函数,前提是您在此文件中导入调度或以某种方式将其作为参数传递。

function dispatchAction(nexState,replace){
   //dispatch 
}

但是我觉得这个解决方案更脏。

我可以非常有效的另一个解决方案是使用容器并在其中调用 componentDidMount。

import React,{Component,PropTypes} from 'react'
import {connect} from 'react-redux'

const propTypes = {
 //
}

function mapStateToProps(state){
//
}

class ComponentContainer extends Component {

  componentDidMount(){
    //dispatch action
  }
  render(){
    return(
      <Component {...this.props}/> //your dumb/stateless component . Pass data as props
    )
  }
} 

export default connect(mapStateToProps)(ComponentContainer)
于 2016-09-29T07:18:35.987 回答
1

一般来说,如果没有在第一次安装/渲染组件时调度的某种触发操作,我认为这是不可能的。您通过使 mapDispatchToProps 不纯来实现这一点。我 100% 同意 Sebastien 的观点,即这是一个坏主意。您还可以将杂质移动到渲染函数,这更糟。组件生命周期方法就是为此而生的!如果您不想写出组件类,他的 HOC 解决方案是有意义的。

我没有太多要补充的,但如果您只想查看实际的 saga 代码,这里有一些伪代码,给出了这样的触发操作(未经测试):

// takes the request, *just a single time*, fetch data, and sets it in state
function* loadDataSaga() {
    yield take(myActionTypes.DATA_GET_REQUEST)
    const data = yield call(fetchData)
    yield put({type: myActionTypes.SET_DATA, data})
}

function* mainSaga() {
    yield fork(loadDataSaga);
    ... do all your other stuff
}

function myReducer(state, action) {
    if (action.type === myActionTypes.SET_DATA) {
         const newState = _.cloneDeep(state)
         newState.whatever.data = action.data
         newState.whatever.loading = false
         return newState
    } else if ( ... ) {
         ... blah blah
    }
    return state
}

const MyStatelessComponent = (props) => {
  if (props.loading) {
    return <Spinner/>
  }
  return <some stuff here {...props.data} />
}

const mapStateToProps = (state) => state.whatever;
const mapDispatchToProps = (dispatch) => {
    // catched by a Saga watcher, and further delivered to a Saga worker that asynchronically fetches data to the store
    dispatch({ type: myActionTypes.DATA_GET_REQUEST });
    return {};
};

加上样板:

const sagaMiddleware = createSagaMiddleware();

export default connect(mapStateToProps, mapDispatchToProps)(MyStatelessComponent);

const store = createStore(
  myReducer,
  { whatever: {loading: true, data: null} },
  applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(mainSaga)
于 2016-10-03T00:59:49.560 回答