Reactjs 在redux组合减速机中,调用所有减速机是否正确?
我有两个减缩器(计数和搜索),我已经组合。当搜索组件分派时,将调用两个减缩器Reactjs 在redux组合减速机中,调用所有减速机是否正确?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我有两个减缩器(计数和搜索),我已经组合。当搜索组件分派时,将调用两个减缩器 这是所有减速器都被调用的预期行为吗 或者,应该只调用最具体的减速器(即搜索)?我必须做什么才能只调用最具体的减速器 以下是搜索、计数和组合减缩器 const initialState = {url:'...'}; function search(state = initialState, action) { if (action.type === 'SEARCH') { ... return sta
const initialState = {url:'...'};
function search(state = initialState, action) {
if (action.type === 'SEARCH') {
...
return state;
}
return state;
}
export default search;
搜索组件如下所示
import React, { Component } from 'react';
import { onSearch as onSearchAction } from '../store/actions/Actions.js';
import { connect } from 'react-redux';
class Search extends Component {
render() {
return (
<>
....
</>
);
}
}
const mapStateToProps = (state) => {
return { url: state.url };
}
const mapDispatchToProps = (dispatch, ownProps) => {
return { onSearch: () => dispatch(onSearchAction()) };
};
const ConnectedSearch = connect(mapStateToProps, mapDispatchToProps)(Search);
export default ConnectedSearch;
这是所有减速器都被调用的预期行为吗
对
我必须做什么才能只调用最具体的减速器
嗯,你可以编写一个自定义的减速机来实现这一点,但我不确定它的好处是什么。大概您会编写这样的代码:“如果是这个动作,或者这个动作,或者这个动作,那么调用reducer 1;否则调用reducer 2”。但是检查动作类型是reducer 1已经在做的事情,所以您只是在复制逻辑。为什么不给两个减速机打电话,让他们处理或忽略他们关心或不关心的事情呢
import CountReducer from './CountReducer.js';
import SearchReducer from './ApiReducer.js';
import { combineReducers } from 'redux'
const reduce = combineReducers({
count: CountReducer,
search: SearchReducer
});
export default reduce;
import React, { Component } from 'react';
import { onSearch as onSearchAction } from '../store/actions/Actions.js';
import { connect } from 'react-redux';
class Search extends Component {
render() {
return (
<>
....
</>
);
}
}
const mapStateToProps = (state) => {
return { url: state.url };
}
const mapDispatchToProps = (dispatch, ownProps) => {
return { onSearch: () => dispatch(onSearchAction()) };
};
const ConnectedSearch = connect(mapStateToProps, mapDispatchToProps)(Search);
export default ConnectedSearch;
export function onSearch() {
return {
type: "SEARCH",
url: '...'
}
}