【问题标题】:How to warn react component when redux saga put a success action?当 redux saga 执行成功操作时如何警告反应组件?
【发布时间】:2019-03-16 15:00:40
【问题描述】:

我正在使用 redux 操作模式(REQUEST、SUCCESS、FAILURE)和 redux saga。我就这样制作了一个观察者和工人传奇:

import axios from 'axios';
import { put, call, takeEvery } from 'redux-saga/effects';
import * as actionTypes from 'constants/actionTypes';
import * as actions from 'actions/candidates';
const { REQUEST } = actionTypes;

// each entity defines 3 creators { request, success, failure }
const { fetchCandidatesActionCreators, addCandidateActionCreators } = actions;

const getList = () => axios.get('/api/v1/candidate/');

// Watcher saga that spawns new tasks
function* watchRequestCandidates() {
  yield takeEvery(actionTypes.CANDIDATES[REQUEST], fetchCandidatesAsync);
}

// Worker saga that performs the task
function* fetchCandidatesAsync() {
  try {
    const { data } = yield call(getList);
    yield put(fetchCandidatesActionCreators.success(data.data));
  } catch (error) {
    yield put(fetchCandidatesActionCreators.failure(error));
  }
}


const postCandidate = params => axios.post('/api/v1/candidate/', params).then(response => response.data).catch(error => { throw error.response || error.request || error; });

// Watcher saga that spawns new tasks
function* watchAddCandidate() {
  yield takeEvery(actionTypes.ADD_CANDIDATE[REQUEST], AddCandidateAsync);
}

// Worker saga that performs the task
function* AddCandidateAsync({ payload }) {
  try {
    const result = yield call(postCandidate, payload);
    yield put(addCandidateActionCreators.success(result.data));
  } catch (error) {
    yield put(addCandidateActionCreators.failure(error));
  }
}

export default {
  watchRequestCandidates,
  fetchCandidatesAsync,
  watchAddCandidate,
  AddCandidateAsync,
};

我的 reducer 有两个标志:isLoading 和 success。两个标志都会根据请求、成功和失败操作而变化。

问题是我希望我的组件在成功操作置于 redux 状态时呈现不同的东西。我想在每次发生 _success 动作时警告组件!

我第一次使用的标志很好,但是我希望它们在组件安装或用户单击按钮时重置,因为我的组件是一个表单,我希望用户将许多表单发布到服务器。

最好的做法是什么?

我唯一能想到的就是创建一个 _RESET 操作,当用户单击按钮以填写其他表单以及安装组件时将调用该操作,但我不知道这是否是一个好习惯。

【问题讨论】:

  • 听起来您已经掌握了执行此操作所需的所有知识。我认为reset 行动是有道理的。您可以在表单挂载或卸载时调度它。

标签: reactjs redux redux-saga


【解决方案1】:

您需要分配一个高阶组件,也称为容器,它将商店与您的组件连接起来。当使用选择器时,如果该部分状态发生更改,您的组件将自动更新,并将该部分状态作为道具传递给您的组件。 (在 dspatchstateToProps 中定义)

在下面我有一个 Exmaple 组件,它从 redux 状态中选择状态,并将其作为 Exmaple 的 prop 传递。 例如,我可以根据商店中显示的状态使用文本呈现不同的 div 元素。

祝你好运!

 import { connect } from 'react-redux'

    const ExampleComponent = ({ status }) => {
      return (
    <div>
      {status === 'SUCCESS' ? (<div>yaay</div>) : (<div>oh no...</div>)}
    </div>
  )
}

const mapStateToProps = state => {
  return {
    status: state.status
  }
}

const mapDispatchToProps = dispatch => {
  return {}
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ExampleComponent)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多