[英]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.