- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 react 应用程序,它使用 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));
和获取产品的 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 年之前的代码库,否则请不要编写类组件,也请不要使用 connect
和 mapStateToProps
。< br/>类组件是遗留 API,connect
的存在只是为了与这些组件向后兼容。
如今,您应该使用 useSelector
和 useDispatch
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/
我的应用程序中有一个 settings.php 页面,它使用 $GLOBALS 来存储网络应用程序中使用的配置。 例如,他是我使用的一个示例设置变量: $GLOBALS["new_login_page
我正在尝试编译我们在 OS 类上获得的简单操作系统代码。它在 Ubuntu 下运行良好,但我想在 OS X 上编译它。我得到的错误是: [compiling] arch/i386/arch/start
我知道distcp无法使用通配符。 但是,我将需要在更改的目录上安排distcp。 (即,仅在星期一等“星期五”目录中复制数据),还从指定目录下的所有项目中复制数据。 是否有某种设计模式可用于编写此类
是否可以在config.groovy中全局定义资源格式(json,xml)的优先级,而不是在每个Resource上指定?例如,不要在@Resource Annotation的参数中指定它,例如: @R
是否有一些简单的方法来获取大对象图的所有关联,而不必“左连接获取”所有关联?我不能只告诉 Hibernate 默认获取 eager 关联吗? 最佳答案 即使有可能有一个全局 lazy=false(谷歌
我正在尝试实现一个全局加载对话框...我想调用一些静态函数来显示对话框和一些静态函数来关闭它。与此同时,我正在主线程或子线程中做一些工作...... 我尝试了以下操作,但对话框没有更新...最后一次,
当我偶然发现 this question 时,我正在阅读更改占位符文本。 无论如何,我回去学习了占位符。一个 SO 的回答大致如下: Be careful when designing your pl
例如,如果我有这样的文字: "hello800 more text 1234 and 567" 它应该匹配 1234 和 567,而不是 800(因为它遵循 hello 的 o,这不是一个数字)。 这
我一直在尝试寻找一种无需使用 SMS 验证系统即可验证电话号码(Android 和 iPhone)的方法。原因纯粹是围绕成本。我想要一个免费的解决方案。 我可以安全地假设 Android 操作系统会向
解决此类问题的规范 C++ 设计模式是什么? 我有一些共享多个类的多线程服务器。我需要为大多数类提供各种运行时参数(例如服务器名称、日志记录级别)。 在下面的伪 C++ 代码中,我使用了一个日志记录类
这个问题在这里已经有了答案: Using global variables in a function (25 个答案) 关闭 9 年前。 我是 python 的新手,所以可能有一个简单的答案,但我
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Does C++ call destructors for global and class static
我正在尝试使用 Objective-C 中的 ArrayList 的等价物。我知道我必须使用 NSMutableArray。我想要一个字符串列表 (NSString)。关键是我的列表应该可以从我类(c
今天刚开始学习 Android 开发,我找不到任何关于如何定义 Helper 类或将全局加载的函数集合的信息,我会能够在我创建的任何 Activity 中使用它们。 我的计划是创建(至少目前)2 个几
为什么这段代码有效: var = 0 def func(num): print num var = 1 if num != 0: func(num-1) fun
$GLOBALS["items"] = array('one', 'two', 'three', 'four', 'five' ,'six', 'seven'); $alter = &$GLOBALS
我想知道如何实现一个可以在任何地方使用您自己的设置的全局记录器: 我目前有一个自定义记录器类: class customLogger(logging.Logger): ... 该类位于一个单独的
我需要使用 React 测试库和 Jest 在我的测试中模拟不同的窗口大小。 目前我必须在每个测试文件中包含这个beforeAll: import matchMediaPolyfill from 'm
每次我遇到单例模式或任何静态类(即(几乎)只有静态成员的类)的实现时,我想知道这是否实际上不是一种黑客行为,因此只是为了设计而严重滥用类和实例的原则单个对象,而不是设计类和创建单个实例。对我来说,看起
这个问题在这里已经有了答案: Help understanding global flag in perl (2 个回答) 7年前关闭。 my $test = "There was once an\n
我是一名优秀的程序员,十分优秀!