在axios中渲染React组件

时间:2018-04-02 09:29:13

标签: reactjs axios

我刚刚开始学习React,我正在尝试使用第三方服务器API创建一个简单的应用程序来搜索空缺。该应用程序由forminput组成,在submit上,它使用axios向服务器发送请求,获取响应并且必须呈现它。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import "bootstrap/dist/css/bootstrap.css";
import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.hh.ru/vacancies/',
  headers: {
        'User-Agent': 'React App/1.0 (tatyana.fomina.1986@gmail.com)', 
        'HH-User-Agent': 'React App/1.0 (tatyana.fomina.1986@gmail.com)'
    }
});

const Header = () => {
    return <h1>Поиск вакансий на HH.ru</h1>
}

const Vacancies = props => {
    return <div>Some Text</div>
}

class SearchForm extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            position: ''
        }

        this.handlePositionChange = this.handlePositionChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handlePositionChange(e) {
            this.setState({
                [e.target.name]: e.target.value
            });
        }

    handleSubmit(e) {
        e.preventDefault();

        var formButton = document.getElementById('form-button');
        formButton.disabled = true;

        var position = this.state.position;
        console.log(position);

        if ( position ) {
            instance({
                    method: 'GET',
                    url: '?text=' + position,
                    data: {
                        position: position
                    }
                })
                .then(function(response) {
                    console.log(response.data);
                    formButton.disabled = false;
            })
               .catch(function (error) {
                console.log(error);
              });
        } else {
            formButton.disabled = false;
        }
    }

    render() {
        return (
            <form className="form search-form" onSubmit = { this.handleSubmit }>
                <div className="form-row">
                    <div className="form-group col-md-8">
                        <label htmlFor="position"> Position *
                            < /label>
                                <input type="text" className="form-control" name="position" id="position" placeholder="Position" onChange={ this.handlePositionChange } value={ this.state.position } />
                    </div>

                    <div className="form-group col-md-4 d-flex flex-column justify-content-end">
                        <input id = 'form-button'
                        className = 'btn btn-primary'
                        type = 'submit'
                        placeholder = 'Send' / >
                    </div>
                </div>
            </form>
        )
    }
}

class App extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
            <div className="col-12">
                <Header />
                <SearchForm />
                <Vacancies />
            </div>
        </div>
      </div>
    );
  }
}

export default App;

我在渲染<Vacancies />方面遇到问题,是否有可能动态渲染它并每次在每次新请求和服务器响应时更新数据?

1 个答案:

答案 0 :(得分:1)

你想要的是Vaconcies获取更新的数据,这是你在SearchForm的API请求之后得到的,在这种情况下你需要重组你的组件并在父项中提升动作并将数据作为道具传递到兄弟姐妹组件

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import "bootstrap/dist/css/bootstrap.css";
import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.hh.ru/vacancies/',
  headers: {
        'User-Agent': 'React App/1.0 (tatyana.fomina.1986@gmail.com)', 
        'HH-User-Agent': 'React App/1.0 (tatyana.fomina.1986@gmail.com)'
    }
});

const Header = () => {
    return <h1>Поиск вакансий на HH.ru</h1>
}

const Vacancies = props => {
    return <div>Some Text</div>
}

class SearchForm extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            position: ''
        }

        this.handlePositionChange = this.handlePositionChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handlePositionChange(e) {
            this.setState({
                [e.target.name]: e.target.value
            });
        }

    render() {
        return (
            <form className="form search-form" onSubmit = { (e) => this.handleSubmit(e, this.state.position) }>
                <div className="form-row">
                    <div className="form-group col-md-8">
                        <label htmlFor="position"> Position *
                            < /label>
                                <input type="text" className="form-control" name="position" id="position" placeholder="Position" onChange={ this.handlePositionChange } value={ this.state.position } />
                    </div>

                    <div className="form-group col-md-4 d-flex flex-column justify-content-end">
                        <input id = 'form-button'
                        className = 'btn btn-primary'
                        type = 'submit'
                        disabled={this.props.disableSubmit}
                        placeholder = 'Send' / >
                    </div>
                </div>
            </form>
        )
    }
}

class App extends Component {
      state = {
        disableSubmit: false;
      }
      handleSubmit = (e, position) => {
        e.preventDefault();

        this.setState({disableSubmit : true});
        console.log(position);

        if ( position ) {
            instance({
                    method: 'GET',
                    url: '?text=' + position,
                    data: {
                        position: position
                    }
                })
                .then(function(response) {
                    this.setState({data: response.data, disableSubmit:false});
            })
               .catch(function (error) {
                console.log(error);
              });
        } else {
            this.setState({disableSubmit : false});
        }
    }
  render() {
    return (
      <div className="container">
        <div className="row">
            <div className="col-12">
                <Header />
                <SearchForm handleSubmit = {this.handleSubmit} disableSubmit={this.state.disableSubmit}/>
                <Vacancies data={this.state.data}/>
            </div>
        </div>
      </div>
    );
  }
}

export default App;

同样在使用React时,您必须确保自己没有修改DOM元素并以React方式处理所有交互。例如,您可以使用道具或州来控制提交按钮的禁用状态。