[英]REACT - REDUX how to update the global state of a redux app in child component that fetched data in parent when app is mounted
我有一個反應應用程序,它使用 redux thunk 獲取數據,並在安裝應用程序時將其設置為主組件的全局狀態,然后我有一個子組件,其中填寫了一個表單,然后我想根據輸入更新狀態此表單,然后重定向到另一個更新了全局狀態的組件。
主要組成部分是這樣的:
mainComponent.js
import React, { Component } from 'react';
import {Routes, Route, Navigate, useParams, useNavigate} from 'react-router-dom'; //Switch changed to routes Also redirect is changed to Navigate since version 6
import {connect} from 'react-redux';
import { useLocation } from 'react-router-dom';
import Store from './store-components/StoreComponent';
import {fetchProducts} from '../redux/ActionCreators';
// --------Hook to use withRouter from v5 in actual v6-----------------
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
return (
<Component
navigate={navigate}
location={location}
params={params}
{...props}
/>
);
};
return Wrapper;
};
const mapStateToProps = (state) => {
return{
products: state.products,
}
}
const mapDispatchToProps = dispatch => ({
fetchProducts: () => { dispatch(fetchProducts())},
});
class Main extends Component {
componentDidMount() {
this.props.fetchProducts();
}
render(){
return (
<div>
<Header/>
<Routes>
<Route path = "/login" element = {<LoginComponent/>}/>
<Route path="/home" element={<Home products={this.props.products}/>}/>
<Route exact path="/store" element= {<Store products={this.props.products} />} />
<Route path="*"element={<Navigate to="/home" />} />
{/* Instead of redirect the above is needed to redirect if there is no matched url*/}
</Routes>
<Footer location={this.props.location}/>
</div>
);
}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Main));
和獲取產品的減速器:
ActionCreator.js
import * as ActionTypes from './ActionTypes';
import { baseUrl } from '../shared/baseUrl';
// -------------------------- products--------------------------------
//-- products thunk
export const fetchProducts = () => (dispatch) => {
dispatch(productsLoading(true));
return fetch(baseUrl +'products')
.then(response => {
if (response.ok){
return response;
}
else{
var error = new Error('Error '+response.status+': '+response.statusText)
error.response = response;
throw error;
}
},
error =>{
var errmess=new Error(error.message);
throw errmess;
})
.then(response => response.json())
.then(products => dispatch(addProducts(products)))
.catch(error => dispatch(productsFailed(error.message)));
}
// thunk
// this is something I tried to solve my problem but is not working
export const fetchProductsBuscador = (param) => (dispatch) => {
dispatch(productsLoading(true));
return fetch(baseUrl +'products'+'/'+param)
.then(response => {
if (response.ok){
return response;
}
else{
var error = new Error('Error '+response.status+': '+response.statusText)
error.response = response;
throw error;
}
},
error =>{
var errmess=new Error(error.message);
throw errmess;
})
.then(response => response.json())
.then(products=> dispatch(addProducts(products)))
.catch(error => dispatch(productsFailed(error.message)));
}
我要更新狀態的表單所在的組件是
Finder.js
import React, {Component} from 'react';
//this is a service to use navigate in this class component in order to redirect to the //component i want to render the updated state
import { withNavigate } from '../../services/withNavigate';
import { Navigate } from 'react-router-dom';
import { connect } from 'react-redux';
import {fetchProductsBuscador} from '../../redux/ActionCreators';
// this component will be used to search for a product
// the user will select the type of product, marca, linea, modelo,
// the server will handle the search and return the products that match the search criteria by using query parameters
// so the first input will be the tipo, so when the user selects a tipo, the server will return the marcas that are available for that tipo
// then the user will select a marca, and the server will return the lineas that are available for that marca
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
const mapStateToProps = (state) => {
return{
products: state.products,
}
}
const mapDispatchToProps = dispatch => ({
fetchProductsBuscador: (param) => { dispatch(fetchProductsBuscador(param))},
});
class Finder extends Component {
constructor(props){
super(props);
this.state = {
tipo: '',
marca: '',
linea: '',
marcaDropdown: [],
lineaDropdown: [],
modeloDropdown: [],
modeloInput: '',
// the url will be updated with the new values
url: baseUrl+'buscaproduct'
};
// bind the functions handlers to the constructor to make them available
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmit(event){
event.preventDefault()
// redirect to the store component with the search criteria
// the search criteria will be passed as query parameters
var tipo = this.state.tipo
var marca = toTitleCase(this.state.marca)
var linea = this.state.linea
this.props.fetchProductsBuscador('/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea)
.then((response)=>{
this.props.navigate('/store',{
state:{
products:response.data
}
})
}).catch((error)=>{
console.log(error)
});
}
// this function will handle the input change
// when a type is selected, the marca will be updated and the url will be updated,
// an async call will be made to the server to get the marcas that are available for that tipo
// then the marca will be updated with the data from the server
// and the url will be updated with the new marca
// and so on
handleInputChange(event){
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
// if the user selects a tipo, then the marca will be updated with the marcas that are available for that tipo
// and the url will be updated with the new marca
if(name === 'tipo'){
axios.get(baseUrl+'buscavehiculo/?tipo=' + value)
.then((response) => {
this.setState({
marcaDropdown: response.data
});
console.log('marcas',response.data);
})
.catch((error) => {
console.log(error);
});
}
// if the user selects a marca, then the linea will be updated with the lineas that are available for that marca
// and the url will be updated with the new linea
if(name === 'marca'){
axios.get(baseUrl+'buscavehiculo/?tipo=' +this.state.tipo + '&marca=' + value)
.then((response) => {
this.setState({
lineaDropdown: response.data
});
})
.catch((error) => {
console.log(error);
});
}
}
render(){
return(
// HERE IS the form i suppose is not needed to show as this just give the values of //above
);
}
}
export default withNavigate(connect(mapStateToProps,mapDispatchToProps) (Finder));
我嘗試的另一種方法是在 handleSubmit 中使用handleSubmit
:
handleSubmit(event){
event.preventDefault()
// redirect to the store component with the search criteria
// the search criteria will be passed as query parameters
var tipo = this.state.tipo
var marca = toTitleCase(this.state.marca)
var linea = this.state.linea
axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )
.then((response) => {
console.log('response.data',response.data)
this.props.navigate("/store",{
state:{
products:response.data
}
});
})
.catch((error) => {
console.log(error)
})
}
上面可以重定向但呈現第一次安裝應用程序時使用 redux thunk 獲取的數據,而不是使用 axios 更新的數據,axios 完成了獲取過濾數據的工作但無法更新狀態和 redux 方法我得到錯誤
Uncaught TypeError: can't access property "then", this.props.fetchProductsBuscador(...) is undefined
我怎樣才能更新狀態,以便當我在 handleSubmit 中重定向時,只呈現我想要的和在表單中過濾的數據,而不是第一次獲取的數據?
除非您使用的是從未更新到 React 16.8 的 2019 年之前的代碼庫,否則請不要編寫類組件,也請不要使用connect
和mapStateToProps
。
類組件是遺留的 API, connect
的存在只是為了向后兼容它們。
如今,您應該使用useSelector
和useDispatch
掛鈎,並且您應該在所有需要它的組件中使用它們——在父組件或子組件中分派一個動作沒有區別——只要在你需要的地方分派一個動作,就可以了在任何需要的地方使用useSelector
訂閱存儲值。
綜上所述,您可能還在使用一種非常過時的 Redux 風格,即使您沒有在這里展示它:現代 Redux 不使用帶有switch
語句和ACTION_TYPE
字符串常量的手寫 reducer。 createSlice
為您處理所有這些。
此外,您不需要像在此處那樣手動編寫提取邏輯,RTK Query 會為您處理該部分 -並且“意外”它也會在此處處理您的問題 - 您的緩存條目將由過濾器分開,並且何時您使用不同的過濾器重新安裝原始組件,它不會首先顯示舊值。
一般來說,我強烈建議您閱讀為什么 Redux Toolkit 以及今天如何使用 Redux ,然后按照官方的 Redux 教程進行操作,因為您所關注的資源似乎已經過時了三年多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.