[英]react -redux component does not re-render after state change
我一直在嘗試我的組件不會重新呈現自己。 下面是我的 reducer 代碼,我已盡一切努力不改變狀態。 在我的組件代碼中,在 render 方法中,我有一個日志語句 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 看起來像下面我計划最終將有效負載傳遞給 reducer 但目前我不是
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
});
})
};
}
ActionType常量
export const GET_SEARCH = "GET_SEARCH";
您沒有更新searchType
值,該值被硬編碼為 string new string
。 嘗試從操作中設置新狀態,例如:
return { ...state, searchType: action.payload};
或檢查此https://jsfiddle.net/xt3sqoc6/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
});
};
}
您可以使用componentDidUpdate(prevProps, prevState)
。 它在更新發生后立即被調用,您可以將當前道具與以前的道具進行比較。 使用它你可以通過改變state
來重新渲染你的組件
componentDidUpdate(prevProps) {
if (this.props.SearchType !== prevProps.SearchType) {
//Do whatever needs to happen!
}
}
您可以在componentDidUpdate
中立即調用setState()
,但請注意,它必須包含在如上例所示的條件中,否則會導致無限循環。
希望這對你有幫助。 有疑問請隨意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.