Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 仅当状态不同时才重新设置状态_Reactjs_Redux_React Redux - Fatal编程技术网

Reactjs 仅当状态不同时才重新设置状态

Reactjs 仅当状态不同时才重新设置状态,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我正在使用Redux进行状态管理,但遇到了一个问题。我的问题是,我喜欢只在状态不同时设置状态。让我通过我的代码来澄清我的问题 // MyComponent.jsx const [query, setQuery] = useState(''); useEffect(() => { if(query.length) { let {search, cancel} = searchContent(query); search.then(res =>

我正在使用Redux进行状态管理,但遇到了一个问题。我的问题是,我喜欢只在状态不同时设置状态。让我通过我的代码来澄清我的问题

// MyComponent.jsx
 const [query, setQuery] = useState('');

  useEffect(() => {
    if(query.length) {
      let {search, cancel} = searchContent(query);

      search.then(res => 
        setSearchResult(res.data)
        ).catch(e => {
          if(axios.isCancel(e)){
            return;
          }
        })
      return () => cancel();
    }else{
      setSearchResult(null);
    }
  }, [query, setSearchResult])
上面是我应该设置搜索状态的组件

// action.js
export const SET_SEARCH_RESULT = 'SET_SEARCH_RESULT';

export const setSearchResult = (val) => ({
  type: SET_SEARCH_RESULT,
  searchResult: val,
});

//reducer.js
import { SET_SEARCH_RESULT } from './article.action';

const INITIAL_STATE = {
  searchResult: null
}

const articleReducer = (state=INITIAL_STATE, action) => {
  switch (action.type) {
    case SET_SEARCH_RESULT:
    return {
      ...state,
      searchResult: action.searchResult
    }
    default:
      return state
  }
}

我可以使用redux设置状态,而且效果很好。然而,我的问题是,即使初始状态为null,当useEffect函数最初运行时,我的状态也设置为null

我的问题是如何使用redux,使其仅在状态不同时运行


提前感谢。

您可以有条件地签入articleReducer,但是这不会有什么区别,因为当您使用选择器时,它不会导致重新渲染,因为访问的值是相同的,除非您更改ReferenceHanks以获得快速回答。如果redux设置为相同的值,我实际上不想运行它。初始“searchResult”为null,但实际上它也将searchResult设置为null。如何防止这种行为?