我正在为我的一个项目使用react redux。我正在使用mapStateToProps()
来获得道具。但是道具正在延迟。起初,我console.log
道具是空的,但几秒钟后它们被装上,我有了一些道具。单击按钮后,我需要立即加载道具。我的代码看起来像这样。
import React from "react";
import { connect } from "react-redux";
import "react-loader-spinner/dist/loader/css/react-spinner-loader.css";
import SearchBar from "./search-bar";
import NavBar from "../navBar";
import Footer from "../footer";
import {
searchProduct,
fetchProducts,
setLoading,
saveKeyword,
filterProducts
} from "../../../_actions/search.action";
import { Link } from "react-router-dom";
class ContainingResult extends React.Component {
onClick = e => {
this.props.fetchProducts(this.props.text);
this.props.saveKeyword(this.props.text);
};
render() {
const { text, product } = this.props;
console.log("TEXT", text);
const { loading } = this.props;
//Here these props are not loaded at first. But after some seconds I get them
console.log("Containing", this.props);
return (
<React.Fragment>
<NavBar></NavBar>
<SearchBar></SearchBar>
<div class="card">
<h5 class="card-header">Results</h5>
<div class="card-body">
<h5 class="card-title">{text}</h5>
<p class="card-text">
With supporting text below as a natural lead-in to additional
content.
</p>
<Link to={`/dashboard/search?q=${text}`}>
<button onClick={this.onClick} class="btn btn-primary">
See More
</button>
</Link>
</div>
</div>
<Footer></Footer>
</React.Fragment>
);
}
}
const mapStateToProps = state => ({
loading: state.product.loading,
text: state.product.text,
product: state.product.products
});
export default connect(mapStateToProps, {
searchProduct,
fetchProducts,
setLoading,
saveKeyword,
filterProducts
})(ContainingResult);
action.js
export const fetchProducts = text => dispatch => {
console.log("Called from ", text);
const api = `/Search?searchString=${text}`;
axios
.get(apiBaseUrl + api, { headers: { Authorization: `Bearer ${token}` } })
.then(res => {
console.log("hello", api);
try {
dispatch({
type: FETCH_PRODUCTS,
payload: res
});
} catch (err) {
console.log("error", err);
}
});
};
reducer.js
import {
SEARCH_PRODUCTS,
FETCH_PRODUCTS,
LOADING,
PAGINATE,
PRODUCT_DETAILS,
USER_PROFILE,
KEYWORD,
FILTERED_PRODUCTS
} from "../_actions/types";
const initialState = {
text: "",
products: [],
loading: false,
product: [],
profile: [],
filter: [],
pagination: {
totalRecords: 0,
totalPages: 0,
pageLimit: 4,
currentPage: 1,
startIndex: 1,
endIndex: 0
}
};
export default (state = initialState, action) => {
case FETCH_PRODUCTS:
console.log(
"action -- FetchProducts",
action,
"state -- FetchPro",
state
);
return {
...state,
products: action.payload,
loading: false,
totalRecords: action.payload.length
};
}
答案 0 :(得分:0)
我想BashOperator
正在执行一些异步操作,并且您正在等待this.props.fetchProducts(this.props.text);
操作来更新商店。
在这种情况下,您希望切换到乐观更新。这意味着更新SUCCESS
操作的状态,并希望请求成功。在REQUEST
操作中,您应将状态恢复为其原始值。
编辑:既然整个代码都可用,那么您在FAILURE
语句中应该有一个default
返回状态。
switch