我有一个react应用程序,它使用redux thunk获取数据,并在安装应用程序时将其设置为主组件的全局状态,然后我有一个子组件,其中填写了一个表单,然后我想根据此表单中的输入更新状态,然后重定向到另一个组件,更新了全局状态。
其主要组成部分是:
主组件.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));
和取产品的还原剂:
操作创建器.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)));
}
而我想要更新状态的表单所在的组件是
查找器.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中重定向时,只呈现我想要的和在表单中过滤的数据,而不是第一次获取的数据?
1条答案
按热度按时间jw5wzhpr1#
除非您使用的是2019年之前版本的代码库,且从未更新到React 16.8,否则请勿编写类组件,也请勿使用
connect
和mapStateToProps
。类组件是一个遗留API,
connect
的存在只是为了向后兼容这些组件。现在,你应该使用
useSelector
和useDispatch
钩子,并且你应该在所有需要它的组件中使用它们--在父组件或子组件中调度一个动作没有区别--只要在你需要的地方调度一个动作,只要在你需要的地方订阅用useSelector
存储值。尽管如此,您可能也在使用一种非常过时的Redux风格,尽管您没有在这里展示它:现代Redux不使用带有
switch
语句和ACTION_TYPE
字符串常量的手写约简器。createSlice
会为您处理所有这些问题。此外,您不需要像这里那样手动编写获取逻辑,RTK Query会为您处理这部分-并且“意外”它也会处理您在这里的问题-您的缓存条目将通过过滤器分隔开,当您使用不同的过滤器重新挂载原始组件时,它不会首先显示旧值。
一般来说,我强烈建议您阅读why Redux Toolkit is how to use Redux today,然后关注the official Redux Tutorial,因为您关注的源代码似乎已经过时三年多了。