如何在react-native中使用FlatList keyExtractor访问行

时间:2018-07-16 14:03:22

标签: react-native

有什么方法可以使用在FlatList中使用keyExtractor设置的键访问行。

我使用FlatList来填充数据,我需要使用它的键分别获取一行,以便更新该行而不重新渲染整个视图。

componentWillMount 上,我使用api调用填充了数据列表数组。

虚拟数组看起来

  

[{{id:“ Usr01”,title:“ Name1”},{id:“ Usr02”,title:“ Name2”},...]

在任何行上按我会得到它的ID时,我需要使用它的键来访问该行。

  

let dataitem = this.state.datalist [id];

当我控制台数据项时,我未定义

我将id设置为keyExtractor中的键,有什么方法可以做到这一点。

我的代码如下

FlatListScreen.js

export default class FlatListScreen extends Component { 
constructor(props)
{
super(props);
this.state={
    datalist: [],
}
}

componentWillMount() {
ApiHandler.getlistitem('All').then(response =>{
    this.setState({datalist: response});
});
}

_keyExtractor = (item, index) => item.id;

_onPressItem = (id) => {
let dataitem = this.state.datalist[id];
const { name } = dataitem
const newPost = {
    ...dataitem,
    name: name+"01"
}

this.setState({
    datalist: {
        ...this.state.datalist,
        [id]: newPost
}
})
};


_renderItem ({ item }) {
    return (
    <MyListItem
    id={item.id}
    onPressItem={this._onPressItem}
    title={item.title}
    />
    )
} 


render() {
return ( 

<FlatList
    data={this.state.datalist}
    keyExtractor={this._keyExtractor}
    renderItem={this._renderItem}
/>


    );
}

}
}

MyListItem.js

export default class MyListItem extends Component {
constructor(props) {
    super(props)
    this.state = {
        title: '',
        id: ''
    }
}

componentWillMount() {
    const { title, id } = this.props

    this.setState({ title, id })
}

componentWillReceiveProps(nextProps) {
    const { title, id } = nextProps

    this.setState({ title, id })
}


shouldComponentUpdate(nextProps, nextState) {
    const { title} = nextState
    const { title: oldTitle } = this.state
    return title !== oldTitle
}
render() {
    return (
    <View>
    <TouchableOpacity onPress={() =>this.props.onPressItem({id:this.state.id})}>
        <View>
        <Text>
            {this.props.title}
        </Text>
        </View>
    </TouchableOpacity>
    </View>

    );
}
}

1 个答案:

答案 0 :(得分:0)

我认为正在改变

onPressItem({id:this.state.id});

onPressItem(this.state.id);在您的子组件中

OR

_onPressItem = (id) => { } 

_onPressItem = ({id}) => { } 

您父组件中的

将解决此问题。

当您将其作为对象从子级发送到父级时,您也可以像这样访问它

let dataitem = this.state.datalist[id.id];
相关问题