状态更改后,React-Redux重新呈现

时间:2020-04-10 12:38:40

标签: reactjs redux

我试图理解React + Redux。因此,现在我正尝试从API提取数据,并面临着一个普遍的问题:当我更改Redux状态时,它不会刷新我的容器组件。
我在这里阅读了几个问题,最常见的问题是变异状态和错误的connect使用。我检查了我的代码,一切看起来都很好。我想,问题出在Reqct钩子useState中,在其中我将其称为动作生成器。
代码:
动作生成器

export const requestAccounts = () => ({
  type: 'REQUEST_ACCOUNTS'
});

export const receivedAccounts = (data) => ({
  type: 'RECEIVED_ACCOUNTS',
  data
});

export const requestAccountsError = (errText) => ({
  type: 'RECEIVED_ACCOUNTS_ERROR',
  errText
});

export function getAccounts(clientRef = 1) {

  return async function (dispatch) {
    async function fetchData() {
      let res;
      try {
        res = await fetch("https://wstest.grant.ua/stubs/accnts.json", { //добавить парамтер "номер клиента"
            method: 'GET' // *GET, POST, PUT, DELETE, etc.
        });
        if (res.ok) {
          let resJson = await res.json();
          dispatch(receivedAccounts(resJson.acn_list));
        }
        else {
          dispatch(requestAccountsError('Error during accounts request! Status '+res.status));
        }

      }
      catch (err) {
        dispatch(requestAccountsError(err.message));
      };   
    }
    dispatch(requestAccounts());
    await fetchData();
    /*I supposed that my problem depends on async loading, 
      so I tried to comment all above code and uncomment row below - also, 
      React did not re-render my component...*/
    //dispatch(requestAccountsError("ERROR_MESSAGEEEE"));
  }
}

减速器


const initialState = {
    isFetching : false,
    isError : false,
    errorText : "",
    accounts : []
}

export function acnList(state = initialState, action) {
    switch (action.type) {
      case "RECEIVED_ACCOUNTS":
        return Object.assign({}, state, {
            isFetching: false, 
            isError: false, 
            errorText: "", 
            accounts: action.acnList
          })
/*I tried to write return { errorText: "123" } - also no re-render.. So, problem is not in 
mutating previous state*/
      case "RECEIVED_ACCOUNTS_ERROR":          
        return Object.assign({}, state, {
            isFetching: false, 
            isError: true,
            errorText: "ERRTEXTTTT",
            accounts: []
        })
      case "REQUEST_ACCOUNTS":
        return Object.assign({}, state, {
            isFetching: true, 
            isError: false,
            errorText: "",
            accounts: []
        })
      default:
        return state
    }
}

容器组件

import { connect } from 'react-redux'
import AcnListComponent from '../../MainMenuComponents/AcnListComponent'
import {getAccounts} from '../actions/actions'

const mapStateToProps = (state, ownProps) => {
  return {
    acnList: state.acnList.accounts,
    isError: state.acnList.isError,
    isFetching: state.acnList.isFetching,
    errorText : state.acnList.errorText
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    getAccounts: () => {
      dispatch(getAccounts())
    }
  }
}

const AcnListContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(AcnListComponent)

export default AcnListContainer

最后,我的React组件代码的一部分。

//imports

function AcnListComponent(props) {

  /*here I can see that props are changed sucessfully (according to state). But no re-render!*/
  console.log(props);
  const {t} = props;

  const [isLoading, setIsLoading] = useState(props.isFetching);
  const [accounts, setAccounts] = useState(props.acnList);
  const [emptyMessage, setEmptyMessage] = useState(props.errorText);
  const [isError, setIsError] = useState(props.isError);

  useEffect(() => {
    if ((accounts.length === 0) && !isError) {
        props.getAccounts();
    }
  }, []); //I need to call this effect only once, when component renders
//renders

看起来真的很奇怪,就像魔术一样)
也许我对useEffect做错了,而不是Redux?我需要在组件渲染时发出此请求,然后使用接收到的数据重新渲染。

1 个答案:

答案 0 :(得分:2)

只需更改const [accounts, setAccounts] = useState(props.acnList);

const accounts = props.acnList;

详细了解此blog post

您需要对所有更改的道具执行此操作。

修改

长话短说:

这是将道具复制到状态中的常见错误。

由于道具会随着时间而变化,因此您需要更新状态以反映道具的变化(许多不必要的重新渲染)。最好是直接使用道具。