Установка правильных URL с условным рендерингом при отправке формы в React - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь определить лучший способ справиться с этой ситуацией маршрутизации.В приведенном ниже коде у меня есть компонент, который отображает дочерний элемент при отправке формы, если условие выполняется с использованием this.state.loading.Это выглядит так:

import React, { Component } from 'react';
import './styles/Analytics.css';
import { connect } from 'react-redux';
import { getRecord } from '../actions/recordActions.js';
import WordToSentenceMatch from '../components/Analytics/WordToSentenceMatch'


class Analytics extends Component {
    state = {
        query: '',
        loading: true
    }


    handleChange = e => {
        this.setState({ query: e.target.value})
    }

    componentDidMount = (props) => {
            this.props.getRecord()
        }

    handleSubmit = e => {
        e.preventDefault()
        if (this.state.query !== '') {
            this.setState({loading: false})
        } else{
            alert("Please enter something!")
        }
    }

    render(){
    if (this.state.loading !== true) {
        return <WordToSentenceMatch {...this.state}{...this.props}/>
    }
        return(
        <div id="form-container">
         <svg preserveAspectRatio="none" viewBox="0 0 100 102" height="200" width="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" className="svgcolor-light">
            <path d="M0 0 L50 100 L100 0 Z" fill="#546a7b" stroke="#393d3f"></path>
        </svg>
            <h2>Enter a word below to see what sentence it belongs to.</h2>
            <div id="form">
                <form onSubmit={this.handleSubmit}>
                    <p>
                    <h2 id="form-label">Enter Word:</h2>
                    <input
                        type="text"
                        id="query"
                        query="query"
                        value={this.state.query}
                        onChange={this.handleChange}
                    />
                    </p>
                    <button type="submit" value="Submit">Search Text</button>
                </form>
            </div>
          </div>
        )
    }
}

const mapStateToProps = (state) => {
  return ({
    records: state.allRecords.records
  });
};

Это работает как нужно, но проблема в том, что, когда я рендерим <WordToSentenceMatch />, путь все еще отражает путь родителя.Я хочу реализовать кнопки возврата, чтобы вернуться в контейнер (<Analytics />).Эта же проблема относится к вложенному рендеру в <WordToSentenceMatch />, который рендерит компонент ошибки.Этот компонент ошибки по-прежнему имеет тот же путь, что и контейнер <Analytics />, то есть http://localhost:3000/analytics.Вот код:

import React, { Component } from 'react';
import '../styles/WordToSentenceMatch.css';
import {RichUtils} from 'draft-js';
import ErrorMessage from '../Analytics/ErrorMessage'


class WordToSentenceMatch extends Component {
    state = {
        sentence: ''
    }

    componentWillMount(){
        if (this.props.records.length >= 1) {
            const query = this.props.query
            const content = JSON.parse(this.props.records[this.props.records.length - 1].body.replace(/=>/g, ":")).blocks[0].text
            const matchingSentence = content.split(/[.?!]/).filter(function(n) {
                const regex = new RegExp(query, 'i')
                console.log(regex)
                return regex.test(n)
            });
            this.setState({sentence: matchingSentence})
        }
    }

    render(){
    if (this.state.sentence.length === 0) {
        return <ErrorMessage />
    }
    return(
            <div id="sentence-container">
                    <table>
                            <tr>
                                {this.state.sentence.map(function(sentence){return <td>{sentence}</td>})}
                            </tr>
                    </table>
            </div>
            )
    }
}

export default WordToSentenceMatch;

В настоящее время мои маршруты выглядят так:

class App extends Component {
  render() {
    return (
     <Router>
        <div className="app">
        <NavBar />
            <div>
                <Route exact path='/' component={Home} />
                <Route path='/analytics' component={Analytics} />
                <Route path='/editor' component={TextEditor} />
                <Route path='/error' component={ErrorMessage} />
            </div>
        </div>
      </Router> 
    );
  }
}

export default App;

Я просто хочу убедиться, что я иду по правильному пути, и если я,каков следующий шаг к заботе об этом?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...