簡體   English   中英

無法在反應中的兩個組件之間共享狀態

[英]not able to share state between two components in react

我有兩個組件-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的新手,請為此提供幫助。

提前致謝!!

如果要在調用重定向后在SingleQuestion組件中使用狀態form ,請嘗試此操作。

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

之后,請檢查console.log(this.props.history.location.state.form)

這是在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;


希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM