Я использую реактивный перевод для одного из моих проектов. Я использую 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);
действие. 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);
}
});
};
редуктор. 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
};
}