javascript - React.js 状态 undefined variable

标签 javascript reactjs

我正在尝试将来自 API 的产品存储在 React 组件的状态中,然后将它们映射到组件的渲染函数中,但不知何故 this.state.products未定义

这是我的组件代码(CategoryProducts.js):

class CategoryProducts extends Component{
    constructor(props){
        super(props); 
        this.state = {}
        this.products = new Products(); 
    }

    async componentWillMount(){
        await this.products.getProductsInCategory(this.props.name).then(
            (val) => {
                this.setState({products: val}); 
            }
        )
    }

    render(){
        return(
            <Container className='content-container'> 
                <Row>
                    <Col md={12}>
                        <h4 className="mb-0">{this.props.name}</h4>
                        <hr></hr>
                    </Col>
                </Row>
                <Row>
                    <Col md={2}>
                        Some space for possible filters in the future 
                    </Col>
                    <Col md={10}>
                        {this.state.products.map(function(item, i){
                            console.log(i); 
                        })}
                    </Col>
                </Row>
            </Container>
        );
    }
}

对 API 的调用是异步的,这是相应的代码:

产品.js:

export class Products extends API {

    getProducts() {
        return this.get('/products')
    }
    getCategories(){
        return this.get('/products/categories'); 
    }
    getProductsInCategory(_category){
        return this.get('/products/withcategory/' + _category); 
    }
}

API 类中的这个方法:

async get(_endpoint) {
        let response = await fetch(this.API_url + _endpoint);
        return response.json();
    }

希望有人能帮我解决这个问题

最佳答案

您正在将 componentWillMount 转变为 promise ,以便该部分不会由 RN 执行:

 async componentWillMount(){
        await this.products.getProductsInCategory(this.props.name).then(
            (val) => {
                this.setState({products: val}); 
            }
        )
    }

试试这个:

constructor(props){
        super(props); 
        this.state = {
            products: [] //Or whatever suits you best
         }
        this.products = new Products(); 
    }

 componentWillMount(){
        this.products.getProductsInCategory(this.props.name).then(
            (val) => {
                this.setState({products: val}); 
            }
        )
    }

关于javascript - React.js 状态 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124534/

相关文章:

javascript - 将 redux 存储连接到 nextjs 布局

javascript - 从 API 中提取信息并将其添加到数据库(MEAN 堆栈)

javascript - React 16 中缺少 data-reactroot 属性

javascript - 如何在reactjs中提交时插入数组?

reactjs - React Typescript - 类型参数不可分配给类型参数

javascript - 使用 TypeScript 和 Redux 响应惰性

javascript - jQuery ajax 搜索问题

javascript - 在 Meteor 应用程序中加载音频文件

javascript - 如何使用 jquery 将行名称从 php 传递到 ajax

javascript - 如果当前页面名称未显示在 URL 中,而该页面是 Web 应用程序的默认页面,我该如何获取该页面名称?