【问题标题】:react -redux component does not re-render after state changereact -redux 组件在状态更改后不会重新渲染
【发布时间】:2020-01-21 18:27:31
【问题描述】:

我一直在尝试,我的组件不会重新渲染自己。下面是我的减速器代码,我已经尽一切努力不改变状态。在我的组件代码中,在渲染方法中,我有一个日志语句 console.log("Check Here");我知道组件不会重新渲染,因为此日志在组件第一次渲染时工作,但在 reducer 更改状态后,日志语句没有被调用。在日志中,我可以清楚地看到上一个状态和下一个状态只是我正在更改的一个 SearchType 不同。请帮忙!!

const initState = {

    searchType: ""

};
const techniqueReducer = (state = initState, action) => {
   switch (action.type) {
    case actionTypeConstants.GET_SEARCH:
  {
     return { ...state, searchType: "new string" };    
  }

  default: {
    return state;
  }

}
};

export default myReducer;

我的组件代码如下

import React, { Component } from "react";
import { connect } from "react-redux";
import * as tDispatchers from "../actions/Actions";

const mapStateToProps = state => {
  return {
  
    searchType: state.searchType
  };
};

class SearchCollection extends Component {

  Search= () => {
    this.props.dispatch(tDispatchers.getSearch(document.getElementById("txtSearch").value));
  }
 
  render() {
    console.log("Check Here")

    return (
      <div class="container-fluid">
        <div>

          <input
            type="text"
            id="txtSearch"
            class="form-control"
            placeholder="Enter Search Keywords Here..."
          />
        </div>
        <div>
    <button
            className="btn btn-light btn-sm m-1"
            onClick={this.Search}
          >
            Search
          </button>
         

        </div>
  
      </div>
    );
  }
}

export default connect(mapStateToProps)(SearchCollection);

GetSearch 如下所示 我计划最终将有效负载传递给减速器,但目前我没有

import * as actionTypeConstants from "../action_type_constants";
import axios from "axios";

export function getSearch(searchtext) {

    return dispatchFunction => {
      axios
      .get("<api call>"+searchtext)
      .then(response => {

          dispatchFunction({
            type: actionTypeConstants.GET_SEARCH,
            payload: response.data.data
          });
        })
      };

    }

ActionTypeConstant

export const GET_SEARCH = "GET_SEARCH";

【问题讨论】:

  • return { ...state, SearchType: "new string" };拼写不好?搜索类型?
  • 你能发布有问题的组件代码吗?请包括状态和调度代码的映射。
  • 我已经编辑了这个问题..当我稍微修改代码以发布到这里时发生大写错误
  • 我添加了组件代码
  • @kimi86 能否在 sn-p 中也包含 getSearchTechniquesactionTypeConstants.GET_SEARCH? :)

标签: reactjs react-native redux react-redux


【解决方案1】:

我想您正在使用 redux-thunk 来处理异步操作。但是您不会从 getSearch 返回异步函数。我认为应该是

export function getSearch(searchtext) {
  return dispatchFunction => {
    return axios
      .get("<api call>"+searchtext)
      .then(response => {
        dispatchFunction({
          type: actionTypeConstants.GET_SEARCH,
          payload: response.data.data
        });
      })
  };
}

export function getSearch(searchtext) {
  return async dispatchFunction => {
    const response = await axios
      .get("<api call>"+searchtext);
    dispatchFunction({
      type: actionTypeConstants.GET_SEARCH,
      payload: response.data.data
    });
  };
}

【讨论】:

    【解决方案2】:

    您没有更新searchType 值,它被硬编码为字符串new string。尝试从操作中设置新状态,例如:

    
    return { ...state, searchType: action.payload};
    
    

    或查看https://jsfiddle.net/xt3sqoc6/1/ 并打开您的开发工具以查看重新渲染。

    【讨论】:

      【解决方案3】:

      您可以使用componentDidUpdate(prevProps, prevState)。它在更新发生后立即调用,您可以将当前道具与以前的道具进行比较。使用它,您可以通过更改 state

      来重新渲染您的组件
      componentDidUpdate(prevProps) {
        if (this.props.SearchType !== prevProps.SearchType) {
          //Do whatever needs to happen!
        }
      }
      

      您可以立即在componentDidUpdate 中调用setState(),但请注意,它必须包含在上面示例中的条件中,否则会导致无限循环。

      希望这对您有所帮助。如有疑问,请随意。

      【讨论】:

      • 这仅对本地组件状态有用。 OP 显然在使用基于 sn-p 的 redux。
      • @karlmarxlopez 是对的,这可能与手头的问题无关。您可能不应该在您的 cmets 中如此防御。 :)
      • @segFault 他说这个生命周期只对本地状态有用。但这是错误的。此问题可能会发生在不同的错误中。但使用它你可以检查你的道具变化。
      • @SDushan 我知道componentDidUpdate 做什么,而且我总是阅读文档:)。但是,您明确表示“您可以立即调用 setState”,这与 redux 无关。即使您将 setState 替换为 dispatch 调用,我认为这仍然是一种不好的做法。
      • 我在我的组件中添加了 componentDidUpdate,即使这样也没有触发 componentDidUpdate(prevProps) { if (this.props.searchType !== prevProps.searchType) { console.log("True"); } else { console.log("False"); } }
      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多