React将数据传递给propType

时间:2016-09-29 14:26:44

标签: reactjs

首先,我是react.js的新手。我会对入门套件样板做出反应。我想在propTypes中传递我的请求数据。这可能或我做错了什么?

谢谢

export default class Service extends Component {

static propTypes = {
    services: PropTypes.arrayOf(PropTypes.shape({
        id: PropTypes.string.isRequired,
        slug: PropTypes.string.isRequired,
        title: PropTypes.string.isRequired,
        content: PropTypes.string.isRequired,
        titleHover: PropTypes.string.isRequired,
        contentHover: PropTypes.string.isRequired
    })).isRequired,
};

这是我对graphql的函数请求

async getServices() {
    const resp = await fetch('/graphql', {
        method: 'post',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            query: '{services{id, slug, title, content, titleHover, contentHover}}',
        }),
        credentials: 'include',
    });
    const { data } = await resp.json();
    if (!data || !data.services) throw new Error('Erreur sur le chargement des services !');

    return data.services;
}

我想在de componentWillMount和渲染

中获取我的数据
componentDidMount() {

}

componentWillMount() {

    this.props.services = this.getServices();

}

render(){
    return (
        <div className={'root'}>
            <div className={'container'}>
                <h1>Services</h1>
                <ul>
                    {this.props.services.map((item, index) => (
                        <li key={index} >
                            <h1>{item.title}</h1>
                            <span

                                dangerouslySetInnerHTML={{ __html: item.content }} />
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    );
}
}

1 个答案:

答案 0 :(得分:0)

组件无法单独设置其属性,您应该以状态管理您的服务:

componentWillMount() {
    this.setState({
        services: await this.getServices()
    })
}

并在渲染功能中(注意这个。状态 .services):

<ul>
    {this.state.services.map((item, index) => (
        <li key={index} >
            <h1>{item.title}</h1>
            <span

                dangerouslySetInnerHTML={{ __html: item.content }} />
        </li>
    ))}
</ul>

有关documentation

中州的更多信息

<强> 修改

此外,您可以在getServices函数中使用 this.setState ,如此

...
if (!data || !data.services) throw new Error('Erreur sur le chargement des services !');

this.setState({
    services: data.services
})

然后,只要您想从API获取服务,就可以调用 this.getServices(),例如 componentWillMount 函数:

componentWillMount() {
    this.getServices()
}
相关问题