无法在反应中的两个组件之间共享状态

时间:2019-03-15 06:47:27

标签: reactjs react-redux

我有两个组成部分:AskQuestion和SingleQuestion

我想将数据从AskQuestion传递到SingleQuestion。 如何在SingleQuestion组件中提供this.state.form内容。

AskQuestion.jsx

import React, { Component } from 'react';
import EditableTagGroup from '../EditableTagGroupComponent/EditableTagGroup';
import { createHashHistory } from 'history'

const history = createHashHistory();

class AskQuestion extends Component {
    constructor(props) {
        super(props)
        this.state = {
            form: {
                Title: '',
                Content: '',
                Tags: sessionStorage.getItem("TG"),
            }
        };
        this.onChange = this.onChange.bind(this);
        this.changeHandler = this.changeHandler.bind(this);
        this.submitHandler = this.submitHandler.bind(this);
    }
    changeHandler(e) {
        e.persist();
        let store = this.state;
        store.form[e.target.name] = e.target.value;
        this.setState(store);
    }
    submitHandler(e) {
        e.preventDefault();
        fetch('cons/ques/create', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(
                {
                    "Request": {
                        "RequestInfo": {
                            "userId": "2"
                        },
                        "RequestPayload": {
                            "Questions": [
                                {
                                    "questionId": 0,
                                    "questionTitle": this.state.form.Title,
                                    "isAnswered": false,
                                    "questionContent": this.state.form.Content,
                                    "tags": [{
                                        "tagId": 1,
                                        "tagName": "Java",
                                        "tagUsage": 1
                                    }]
                                }
                            ]
                        }
                    }
                }

            )
        }).then(res => {
            console.log(res);
            this.redirect();
            return res;
        }).catch(err => err);

    }

    redirect = () => {
        this.props.history.push('/SingleQuestion');
    }

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

    render() {
        const { form } = this.state;
        return (
            <div className="container">
                <h2>ASK A QUESTION</h2>
                <form onSubmit={this.submitHandler}>
                    <div className="form-group">
                        <label htmlFor="Title">Title:</label>
                        <input name="Title" type="text" className="form-control" id={this.state.form.Title} placeholder="Enter Title" onChange={this.changeHandler} />
                    </div>
                    <div className="form-group">
                        <label htmlFor="Content">Content:</label>
                        <textarea type="Content" className="form-control" id={this.state.form.Content} placeholder="Content" name="Content" style={{ height: "300px" }} onChange={this.changeHandler}></textarea>
                    </div>
                    <div className="form-group">
                        <label htmlFor="Tags">Tags:</label>
                        <EditableTagGroup />
                    </div>
                    <button type="submit" className="btn btn-default">Post Question</button>
                    <button type="submit" className="btn btn-default">Discard</button>
                </form>
            </div>

        )
    }
}

export default AskQuestion;

SingleQuestion.jsx

import React, { Component } from 'react';
import './SingleQuestion.css';


class SingleQuestion extends Component {

    constructor(props) {
        super(props)
        this.state = {
        };
    }

    render() {
        return (
            <div class="question-container col-lg-10">
                <div class="question-icons pull-left">
                    <div class="rating">
                        <i class="button rating-up fa fa-thumbs-o-up" aria-hidden="true"></i>
                        <span class="counter">0</span>
                        <i class="button rating-down fa fa-thumbs-o-down" aria-hidden="true"></i>
                    </div>
                </div>

                <div class="result-link pull-left" style={{ paddingLeft: "30px", paddingTop: "55px" }}>
                <h1>{this.props.Title}</h1>
                </div>
            </div>

        )
    }
}


export default SingleQuestion;

我看到了诸如分享状态之类的帖子,但并没有帮助我。我主要看到这样的东西

<SingleQuestion callback=*****/>

如果我喜欢在任何使用此<SingleQuestion ------/>的地方使用该组件,则将呈现我不想使用的组件。我是ReactJS的新手  在这方面帮助我。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

如果要在调用重定向后在form组件中使用状态SingleQuestion,请尝试此操作。

redirect = () => {
  this.props.history.push('/SingleQuestion', {
    form: this.state.form
  });
}

然后检查console.log(this.props.history.location.state.form)

答案 1 :(得分:1)

  

这是在reactjs中的并行组件之间传递数据的示例   

// App.js
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';

import SingleQuestion from './SingleQuestion';
import AskQuestion from './AskQuestion';

class App extends Component {
  state = {
    formData: null
  }
  callbackFormData = (formData) => {
    console.log(formData);
    this.setState({formData: formData});
  }
  render() {
    return (
       <Switch>
          <Route path='/askQuestion' render={() => <AskQuestion callbackFormData={this.callbackFormData}/> } />
          <Route path='/singleQuestion' render={() => <SingleQuestion formData={this.state.formData}/>} />
        </Switch>
    );
  }
}

export default App;


//AskQuestion

import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

class AskQuestion extends Component {

  redirect = () => {
    this.props.history.push("singleQuestion");
  };

  submitHandler = () => {
    let title = document.getElementById('title').value;
    if(title !== '')
    this.props.callbackFormData(title);
    this.redirect();   
  }

  render() {
    return (
      <React.Fragment>
          <input id="title" />
          <button onClick={this.submitHandler}>Post Question</button>         
      </React.Fragment>
    )
    }
}

export default withRouter(AskQuestion);


// SingleQuestion.js
import React, { Component } from "react";

class SingleQuestion extends Component {
  render() {
    return <h1>Title:- {this.props.formData}</h1>; 
 }
}
export default SingleQuestion;


我希望这会有所帮助!