如何将post路由添加到我的react应用程序中

时间:2017-10-20 20:34:53

标签: javascript node.js reactjs

我的组件中有一个带有以下代码的模态,我想在我的代码中添加一个帖子路径来捕获用户的响应。我有Mongo / Mongoose设置以及后端服务器。任何帮助都会很棒,因为我是React的新手!



render() {
		return(
			<div className="modal column y-center">
				<h3>How are you doing?</h3>
				{!this.state.start ? (
					<div className="choices">
						<button onClick={() => this.startRelaxation('ok_images')}>Ok</button>
						<button onClick={() => this.startRelaxation('neutral_images')}>Neutral</button>
						<button onClick={() => this.startRelaxation('anxious_images')}>Anxious</button>
					</div>
				) : (
					<div className="column y-center">
						<div className="image">
							<img src={this.state[this.state.mood][this.state.current_image]}/>
						</div>
						<button onClick={this.nextImage.bind(this)}>Next Image</button>
					</div>
				)}
				<button onClick={this.props.closeModal}>Close</button>
			</div>
		)
	}
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我建议您使用Axios等第三方库连接startRelaxation()函数以向后端执行HTTP请求。

或者,如果您使用的是MongoDB,您可能会发现Parse Server等数据库管理工具非常有用。

答案 1 :(得分:0)

这只是建立在阿曼的帖子之上,但你可以这样做:

&#13;
&#13;
import axios from 'axios';
import React, {Component} from 'react';

class YouComponent extends Component {
        constructor(props){
            super(props);
            this.startRelaxation = this.startRelaxation.bind(this);
        }
        startRelaxation(string){
            axios.post('YourRoute'{'BODY OF REQUEST'})
            .then(data => 'DO STUFF WITH DATA');
        }
        render() {
            return(
                <div className="modal column y-center">
                    <h3>How are you doing?</h3>
                    {!this.state.start ? (
                        <div className="choices">
                            <button onClick={() => this.startRelaxation('ok_images')}>Ok</button>
                            <button onClick={() => this.startRelaxation('neutral_images')}>Neutral</button>
                            <button onClick={() => this.startRelaxation('anxious_images')}>Anxious</button>
                        </div>
                    ) : (
                        <div className="column y-center">
                            <div className="image">
                                <img src={this.state[this.state.mood][this.state.current_image]}/>
                            </div>
                            <button onClick={this.nextImage.bind(this)}>Next Image</button>
                        </div>
                    )}
                    <button onClick={this.props.closeModal}>Close</button>
                </div>
            )
        }
    }
&#13;
&#13;
&#13;

你在startRelation方法中有axios请求,你可以在数据库中做任何你需要做的事情。