React native - 按下按钮时如何在按钮内调用异步函数?

时间:2016-11-14 03:07:27

标签: react-native

我是新来的反应原生

我正在尝试创建搜索页面,搜索栏位于顶部,而结果将显示在其下方。我希望我的搜索按钮调用getsearchlist,状态'data'将被设置,我的搜索列表将被重新呈现。怎么做?当我尝试我的代码时,没有任何事情发生,很快就会出现网络请求失败和'可能未处理的承诺拒绝'

    constructor(props) {
    super(props);
    this.state = {
        data: '',
        text: 'ducati'
    };
    this.getsearchlist = this.getsearchlist.bind(this);

}

async getsearchlist() {
    //console.log(this.state.text);
    let text = this.state.text;
    let response = await fetch('https://www.blabla.com');
    let responseXmlText = await response.text();
    let newsitem = JSON.parse(responseXmlText);
    let data = [];
    for (var i = 0; i < newsitem.length; i++) {
        var content = newsitem[i].content.rendered;
        var title = newsitem[i].title.rendered;
        var link = newsitem[i].link;


        var re = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
        var results = re.exec(content);
        var imgsrc = '';
        if (results != null) {
            imgsrc = results[1];
        }
        data.push({
            title: title,
            content: content,
            img: imgsrc,
            link: link
        })
    }

    this.setState({
        data: data
    })

}

render() {
        var datas = this.state.data;

        return (
        <Container>
            <Header searchBar rounded>
                <InputGroup>
                    <Icon name='ios-search' />
                    <Input placeholder='Search'   onChangeText={(text) => this.setState({text})}
             value={this.state.text}/>
                    <Icon name='ios-people' />
                </InputGroup>
            </Header>


            <Content>
             <Button onPress={this.getsearchlist}>
                    Search
                </Button>
                 <List dataArray={datas}
                    renderRow={(data,sectionID, rowID) =>
                        <ListItem  >
                        <Thumbnail square size={100} source={{uri: data.img}} />

                            <Text style={[  styles.titlestyle]}>{data.title}</Text> 

                        </ListItem>
                    }>
                </List>
                    </Content>
        </Container>



        );

2 个答案:

答案 0 :(得分:3)

使用类似的东西。

getSearchList = async () => {
  .....
  .....
}

当你从Button调用它时,就像你现在调用它一样调用它。

<Button onPress={this.getSearchList} /> Search </Button>

希望有所帮助:)

答案 1 :(得分:1)

现在您可以使用以下语法:

<Button onPress={async () => { ... your async code ... }} />Search</Button>