传递依赖项后会重复调用Useeffect



ListPage.js上从EditPage.js文件导航后(即单击提交按钮后(,我的ListPage.js不会刷新,如果我试图在ListPage.js的useEffect((中传递'value'(即用于渲染仓库数组列表(作为变量,它会一次又一次地调用api。这里我使用react redux来获取api

ListPage.js

import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import { showDATA, regFilterCard, spaceFilterCard } from '../../../redux/dispatchAction';
import {
View,
Text,
SafeAreaView,
ScrollView,
TouchableOpacity,
Modal,
Alert,
Pressable,
} from 'react-native';
import WareCard from '../../components/WareCard/WareCard';
import styles from './styles';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import axios from 'axios';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
function ListPage(props) {
const {navigation, value, detail} = props;
const [modalVisible, setModalVisible] = useState(false);
useEffect(() => {
props.showDATA();
}, [value]);
function spaceFilter(){
setModalVisible(!modalVisible)
props.spaceFilterCard()
}
function registerFilter(){
setModalVisible(!modalVisible)
props.regFilterCard()
}
return (
<SafeAreaView style={styles.page}>
<View style={styles.header}>
<Text style={styles.title}>Warehouses</Text>
<TouchableOpacity onPress={() => setModalVisible(!modalVisible)}>
<MaterialIcon name="filter-alt" style={styles.filter}></MaterialIcon>
</TouchableOpacity>
</View>
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<TouchableOpacity onPress={() => spaceFilter()}>
<Text style={styles.modalText}>Space available</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => registerFilter()}>
<Text style={styles.modalText}>Registered</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
<ScrollView
contentContainerStyle={styles.scrollPage}
showsVerticalScrollIndicator={false}>
{value && value !== undefined && value.length > 0 ?
value.map((data, index) => {
return (
<WareCard
city={data.city}
cluster={data.cluster}
name={data.name}
id={data?.id}
space_available={data.space_available}
type={data.type}
is_live={data.is_live}
navigation={navigation}
is_registered={data.is_registered}
code={data.code}
key={index}
/>
);
})
:
null
}
</ScrollView>
</SafeAreaView>
);
}
function mapStateToProps(state){
return {
value: state.warehouses,
}
}

export default connect(mapStateToProps, {
showDATA,
spaceFilterCard,
regFilterCard,
})(ListPage);

EditPage.js

import React, {useState, useEffect} from 'react';
import {View, Text, SafeAreaView, TextInput, TouchableOpacity} from 'react-native';
import styles from './styles';
import {showCardDetail, editCardDetail} from '../../../redux/dispatchAction';
import {connect} from 'react-redux';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import DropDownPicker from 'react-native-dropdown-picker';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import axios from 'axios';
function EditPage(props) {
const [open, setOpen] = useState(false);
const [lopen, setLopen] = useState(false);
const [value, setValue] = useState(false);
const [lvalue, setLvalue] = useState(false);
const [reg, setReg] = useState();
const [name, setName] = useState();
const [city, setCity] = useState();
const [space, setSpace] = useState();
const [live, setLive] = useState();
const [cluster, setCluster] = useState();
const [editId, setEditID] = useState();
const [items, setItems] = useState([
{label: 'Yes', value: 'Yes'},
{label: 'No', value: 'No'},
]);
const [litems, setLitems] = useState([
{label: 'Yes', value: 'Yes'},
{label: 'No', value: 'No'},
]);
const {navigation, route, detail} = props;
useEffect(() => {
props.showCardDetail(route?.params?.id)
setEditID(route?.params?.id)
setName(detail?.name);
setCity(detail?.city);
setCluster(detail?.cluster);
setSpace(detail?.space_available);
if(detail?.is_registered){
setReg("Yes");
}else{
setReg("No")
}
if(detail?.is_live){
setLive("Yes");
}else{
setLive("No")
}
},[])
function onSubmit(){
setValue(!value)
const profile = {
name,
city,
cluster,
space_available:space,
is_registered:reg == 'Yes' ? true : false,
is_live: live == 'Yes' ? true : false
}
props.editCardDetail(editId, profile);
}
return (
<SafeAreaView style={styles.page}>
<View style={styles.header}>
<TouchableOpacity onPress={() => navigation.navigate('Detail')}>
<MaterialIcon style={styles.clear} name="clear"></MaterialIcon>
</TouchableOpacity>
<Text style={styles.code}>{detail && detail !== undefined ? detail?.code : ''}</Text>
</View>
<View style={styles.inputView}>
<Text style={styles.name}>Name:</Text>
<TextInput
underlineColorAndroid="black"
style={styles.textinput}
onChangeText={(e) => {
setName(e)
}}
value={name && name !== undefined ? name : ''}
/>
</View>
<View style={styles.inputView}>
<Text style={styles.name}>City:</Text>
<TextInput underlineColorAndroid="black" onChangeText={(e) => setCity(e)} value={city && city !== undefined ? city : ''} />
</View>
<View style={styles.inputView}>
<Text style={styles.name}>Cluster:</Text>
<TextInput underlineColorAndroid="black" onChangeText={(e) => setCluster(e)} value={cluster && cluster !== undefined ? cluster : ''} />
</View>
<View style={styles.inputView}>
<Text style={styles.name}>Space Available:</Text>
<TextInput keyboardType='numeric' underlineColorAndroid="black" value={space && space !== undefined ? space.toString() : ''} onChangeText={(e) => setSpace(e)} maxLength={10} />
</View>
<View style={{display:'flex', flexDirection:'row', justifyContent:'space-between'}}>
<View style={styles.inputView}>
<Text style={styles.name}>Registered:</Text>
<DropDownPicker
containerStyle={{
width:wp('30%'),
}}
style={styles.drop}
open={open}
value={reg && reg !== undefined ? reg : ''}
items={items}
setOpen={setOpen}
setValue={setReg}
setItems={setItems}
onChangeValue={val => {
console.log(val, 'val');
setReg(val)
}}
/>
</View>
<View style={styles.inputView}>
<Text style={styles.name}>Live:</Text>
<DropDownPicker
containerStyle={{
width:wp('30%'),
}}
style={styles.drop}
open={lopen}
value={live && live !== undefined ? live : ''}
items={litems}
setOpen={setLopen}
setValue={setLive}
setItems={setLitems}
onChangeValue={val => {
console.log(val, 'val');
setLive(val)
}}
/>
</View>
</View>
<TouchableOpacity style={styles.submit} onPress={() => {
onSubmit()
navigation.navigate('List')
}}>
<Text style={styles.submitText}>SUBMIT</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
function mapStateToProps(state) {
return {
detail: state.cardReducer,
editDetail: state.editReducer
};
}
export default connect(mapStateToProps, {
showCardDetail, editCardDetail
})(EditPage);

dispatchaction.js

import data from '../data.json';
import axios from 'axios';
export const showDATA = () => async dispatch => {
await axios.get("https://datadb122.herokuapp.com/warehouses/")
.then(result => {
console.log('data', result.data);
dispatch({type: 'SHOW_DATA', payload: result.data})
})
.catch(e => console.log(e, 'e'))

};
export const showCardDetail = id => async dispatch => {
await axios.get(`https://datadb122.herokuapp.com/warehouses/${id}`)
.then(result => dispatch({type: 'SHOW_CARD', payload: result.data}))
.catch(e => e,'e')
};

export const editCardDetail = (idd, profile) => async dispatch => {
console.log('idddddddddddddd ', idd, profile);
await axios.patch(`https://datadb122.herokuapp.com/warehouses/${idd && idd !== undefined ? idd : ''}`, profile)
.then(result => {
console.log('edit profile ', profile);
console.log('edit result ', result.data);
dispatch({type: 'EDIT_CARD', payload: result.data})
})
.catch(e => e,'e')
};
export const spaceFilterCard = () => async dispatch => {
await axios.get(`https://datadb122.herokuapp.com/warehouses/`)
.then(result =>  {
let arr = []
result.data.map((d, i) => {
if (d.is_live){
arr.push(d);
}
})
dispatch({type: 'SPACE_FILTER', payload: arr})
})
.catch(e => e,'e')
};
export const regFilterCard = () => async dispatch => {
await axios.get(`https://datadb122.herokuapp.com/warehouses/`)
.then(result =>  {
let arr = []
result.data.map((d, i) => {
if (d.is_registered){
arr.push(d);
}
})
console.log('arrrrrrrrrrr', arr);
dispatch({type: 'REG_FILTER', payload: arr})
})
.catch(e => e,'e')
};

*store.js

/*eslint禁用更漂亮/更漂亮*/

import {createStore, applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk';
import {warehouses} from './reducer';
// import {createLogger} from 'redux-logger';
import logger from 'redux-logger';
import {composeWithDevTools} from 'redux-devtools-extension/developmentOnly';
import {cardReducer} from './showCard';
import { editReducer } from './EditCard';

const middleware = [thunk];
const allReducers = combineReducers({
warehouses,
cardReducer,
editReducer,
});
export const store = createStore(allReducers, applyMiddleware(...middleware));

App.js

import React from 'react';
import ListPage from './src/screens/ListPage/ListPage';
import DetailPage from './src/screens/DetailPage/DetailPage';
import EditPage from './src/screens/EditPage/EditPage';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import { Provider } from 'react-redux';
import {store} from './redux/store';

function App() {
const Stack = createNativeStackNavigator();
return (
<>
{/* <ListPage /> */}
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator screenOptions={{headerShown: false}}>
<Stack.Screen name="List" component={ListPage} />
<Stack.Screen name="Detail" component={DetailPage} />
<Stack.Screen name="Edit" component={EditPage} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
</>
);
}
export default App;

值将被多次更改。所以,道具。显示多次调用的数据。您可以删除数组中的值。尝试此步骤或传递id(何时需要调用props.show数据方法.


useEffect(() => {
props.showDATA();
}, []);

相关内容

  • 没有找到相关文章

最新更新