gpt4 book ai didi

javascript - FlatList 不会在 Prop 更改时重新渲染

转载 作者:行者123 更新时间:2023-11-30 14:29:49 25 4
gpt4 key购买 nike

当 Prop 改变时,我的平面列表不会重新渲染。在这种情况下,我转到另一个页面并添加一个新的列表项,当我回到这个列表时它仍然有旧数据。在我刷新之前,新项目不存在。我为正确的 Prop 设置了额外的数据,但它不起作用。

import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { connect } from 'react-redux';
import { Container, Text, Icon, Left, Right, ListItem, Thumbnail, Body, Content } from 'native-base';
import { removeDog, addDog } from '../actions';

class MyDogs extends Component {

renderList() {
if (this.props.myDogs.lendth === 0) {
return (
<Text>You have no saved dogs</Text>
);
}
return (
<FlatList
extraData={this.props.myDogs}
data={this.props.myDogs}
renderItem={({ item }) => {
return (
<ListItem avatar>
<Left>
<Thumbnail
source={{ uri: item.photo }}
square
/>
</Left>
<Body>
<Text>{item.name}</Text>
<Text note>{item.breed}</Text>
</Body>
<Right>
<Icon name='arrow-forward' />
</Right>
</ListItem>
);
}}
keyExtractor={item => item.id}
/>
);
}

render() {
console.log(this.props.myDogs);
return (
<Container>
<Content>
{this.renderList()}
</Content>
</Container>
);
}
}

const mapStateToProps = state => {
return {
myDogs: state.dogs.myDogs
};
};

export default connect(mapStateToProps, { removeDog, addDog })(MyDogs);

这是我的 reducer

import {
ADD_DOG,
REMOVE_DOG
} from '../actions/types';

const INITIAL_STATE = {
myDogs: [],
rejectedDogs: []
};

export default (state = INITIAL_STATE, action) => {
let breedString = '';
switch (action.type) {
case ADD_DOG:
// ... making breed string removed
breedString = action.payload.breeds.breed.$t;

state.myDogs.push({
name: action.payload.name.$t,
photo: action.payload.media.photos.photo[1].$t,
id: action.payload.id.$t,
breed: breedString.slice(0, -2)
});
return { ...state,
myDogs: state.myDogs
};
default:
return state;
}
};

这里是我组合 reducer 的地方

import { combineReducers } from 'redux';
import FindDogsReducer from './FindDogsReducer';
import BreedReduce from './BreedReducer';
import SettingsReducer from './SettingsReducer';
import DogsReducer from './DogsReducer';


export default combineReducers({
findDogsReducer: FindDogsReducer,
dogs: DogsReducer,
breeds: BreedReduce,
settings: SettingsReducer
});

最佳答案

FlatList 是一个 PureComponent,因此它不会重新渲染,除非给它的引用发生变化。您当前正在使用 push 向您的 myDogs 数组添加一个新对象,这将改变当前状态。

相反,您想要创建一个全新的数组,其中包含当前处于状态的所有狗和您的新狗,它会起作用:

export default (state = INITIAL_STATE, action) => {
let breedString = "";

switch (action.type) {
case ADD_DOG:
breedString = action.payload.breeds.breed.$t;

return {
...state,
myDogs: [
...state.myDogs,
{
name: action.payload.name.$t,
photo: action.payload.media.photos.photo[1].$t,
id: action.payload.id.$t,
breed: breedString.slice(0, -2)
}
]
};
default:
return state;
}
};

关于javascript - FlatList 不会在 Prop 更改时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387834/

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