我正在尝试创建搜索功能。 因此,搜索输入的值实际上已在我的操作中传递,我可以从redux logger中看到这些值。但是,redux saga似乎无法拦截来自动作创建者的有效负载值。当我控制台日志时,它将打印未定义的内容。
操作
//ACTIONS
import SearchActionTypes from "./search.types";
export const SearchActionStart = (value) => ({
type: SearchActionTypes.SEARCH_START,
value
});
export const SearchActionSuccess = (items) => ({
type: SearchActionTypes.SEARCH_SUCCESS,
payload: items,
});
export const SearchActionFailure = (e) => ({
type: SearchActionTypes.SEARCH_FAILURE,
payload: e,
});
搜索组件
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectFieldData } from "../../redux/search/search.selector";
import { SearchActionStart } from "../../redux/search/search.actions";
const SearchComponent = (props) => {
const { searchResults, value } = props;
useEffect(() => {}, []);
const onSearchChange = (event) => {
const { value } = event.target;
searchResults(value);
};
return (
<div>
<input
type="text"
value={value}
onChange={onSearchChange}
/>
</div>
);
};
const mapDispatchToProps = (dispatch) => ({
searchResults: (value) =>
dispatch(SearchActionStart(value)),
});
const mapStateToProps = createStructuredSelector({
searchItem: selectFieldData,
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(SearchComponent);
searchSaga
import {
put,
call,
takeLatest,
all,
} from "redux-saga/effects";
import { SearchImage } from "../../api/search-image";
import Axios from "axios";
import {
SearchActionStart,
SearchActionSuccess,
SearchActionFailure,
} from "./search.actions";
import SearchActionTypes from "./search.types";
function* fetchFieldAsync(value) {
try {
// const images = yield call(SearchImage, value);
console.log(value);
// yield put(SearchActionSuccess(value));
} catch (e) {
yield put(SearchActionFailure(e));
console.log(e);
}
}
export function* fetchFieldStart() {
yield takeLatest(
SearchActionTypes.SEARCH_START,
fetchFieldAsync
);
}
export function* searchFieldSaga() {
yield all([call(fetchFieldAsync)]);
}
rootSaga
import { call, all } from "redux-saga/effects";
import { searchFieldSaga } from "./search/search.saga";
export default function* rootSaga() {
yield all([call(searchFieldSaga)]);
}
请查看此代码沙箱(https://codesandbox.io/s/basic-redux-saga-49xyd?file=/index.js)...您的代码工作正常。在saga函数中,您将获得从动作发送的对象作为参数。您可以将其分解为{value},以将搜索词单独作为参数而不是操作对象。
一个非常愚蠢的错误。 在我的 searchSaga 中,而不是导出监视程序函数 fetchFieldStart 。我错误地导出了中间函数,它是f etchFieldAsync 函数,其功能是获取API。
所以 searchSaga.js 代替:
export function* searchFieldSaga() {
yield all([call(fetchFieldAsync)]);
}