gpt4 book ai didi

javascript - REACT - REDUX 如何更新子组件中 redux 应用程序的全局状态,子组件在安装应用程序时在父组件中获取数据

转载 作者:行者123 更新时间:2023-12-05 05:29:50 25 4
gpt4 key购买 nike

我有一个 react 应用程序,它使用 redux thunk 获取数据,并在安装应用程序时将其设置为主组件的全局状态,然后我有一个子组件,其中填写了一个表单,然后我想根据更新状态此表单中的输入,然后重定向到另一个更新了全局状态的组件。

主要成分是这样的:

ma​​inComponent.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));

和获取产品的 reducer :

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 中使用 axios:

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 年之前的代码库,否则请不要编写类组件,也请不要使用 connectmapStateToProps。< br/>类组件是遗留 API,connect 的存在只是为了与这些组件向后兼容。

如今,您应该使用 useSelectoruseDispatch Hook ,并且您应该在所有需要它的组件中使用它们 - 分派(dispatch) Action 之间没有区别在父组件或子组件中 - 只需在任何需要的地方分派(dispatch)一个操作,并在任何需要的地方使用 useSelector 订阅存储值。

综上所述,您可能还在使用一种非常过时的 Redux 风格,即使您没有在此处展示它:现代 Redux 不使用带有 switch 语句的手写 reducer和 ACTION_TYPE 字符串常量。 createSlice 会为您处理所有这些。
此外,您不需要像在此处那样手动编写获取逻辑,RTK Query 会为您处理该部分 - 并且“意外”它也会在此处处理您的问题 - 您的缓存条目将由过滤器,当您使用不同的过滤器重新安装原始组件时,它不会首先显示旧值。

一般来说,我强烈建议您阅读 why Redux Toolkit is how to use Redux today然后关注the official Redux Tutorial因为您所关注的资源似乎已经过时三年多了。

关于javascript - REACT - REDUX 如何更新子组件中 redux 应用程序的全局状态,子组件在安装应用程序时在父组件中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74838691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com