将状态传递给另一个文件中的组件

时间:2017-10-26 09:05:21

标签: javascript reactjs

我有一个App组件,其中包含一些组件,例如菜单,侧栏,回购等。在菜单组件中有一个搜索栏。当您提交在搜索栏中输入的内容时,它会向https://api.github.com/users/发出请求。然后我将json更改为用户状态。但是如何将数据传递给repos组件?这可能吗?

App.js

import React, { Component } from 'react';
import Sidebar from './layout/Sidebar';
import Menu from './layout/Menu';
import Repos from './githubdata/Repos';
import Followers from "./githubdata/Followers";
import Following from "./githubdata/Following";
import BirthCount from "./githubdata/BirthCount";

class App extends Component{
    render(){
        return(
            <div className="wrapper">
                <Sidebar />
                <div className="main-panel">
                    {* In this component the magic happens *}
                    <Menu />
                    <div className="content">
                        <div className="container-fluid">
                            <div className="row">
                                {* I want to display the data in this component *}
                                <Repos />
                                <Followers />
                                <Following />
                                <BirthCount />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default App;

Menu.js

import React, { Component } from 'react';

class Menu extends Component {
    constructor(props){
        super(props);
        this.state = {
            query: ''
        }
    }

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

    search = () => {
        const BASE_URL = 'https://api.github.com/users/';
        let FETCH_URL = `${BASE_URL}${this.state.query}`;
        console.log('fetchurl', FETCH_URL)

        fetch(FETCH_URL, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(json => {
                const user = json;
                console.log('user json', user);
                this.setState({
                    user
                })
            });
    };

    render(){
        return(
            <div>
                <input onChange={this.handleChange} value=this.state.query} type="text"/>
                <button onClick={this.search}>submit</button>
            </div>
        )
    }
}
export default Menu;

5 个答案:

答案 0 :(得分:2)

将搜索功能移至父组件App

在回购中,用户可以this.props.user

获取

App.js

import React, { Component } from "react";
import Sidebar from "./layout/Sidebar";
import Menu from "./layout/Menu";
import Repos from "./githubdata/Repos";
import Followers from "./githubdata/Followers";
import Following from "./githubdata/Following";
import BirthCount from "./githubdata/BirthCount";

class App extends Component {
  constructor() {
    super();
    this.state = { user };
  }
  search = (query) => {
    const BASE_URL = "https://api.github.com/users/";
    let FETCH_URL = `${BASE_URL}${query}`;
    console.log("fetchurl", FETCH_URL);

    fetch(FETCH_URL, {
      method: "GET"
    })
      .then(response => response.json())
      .then(json => {
        const user = json;
        console.log("user json", user);
        this.setState({
          user
        });
      });
  };

  render() {
    return (
      <div className="wrapper">
        <Sidebar />
        <div className="main-panel">
          {/* In this component the magic happens */}
          <Menu search={this.search.bind(this)} />
          <div className="content">
            <div className="container-fluid">
              <div className="row">
                {/* I want to display the data in this component */}
                <Repos user={this.state.user} />
                <Followers />
                <Following />
                <BirthCount />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

答案 1 :(得分:1)

是的,这是可能的。你必须使用名为props https://facebook.github.io/react-native/docs/props.html

的东西
// APP.JS
.....
<div className="row">
   {* I want to display the data in this component *}
        <Repos data={dataToBePassed} />
        <Followers />
        <Following />
        <BirthCount />
   </div>
.....


// REPOS.JS
...
render(){
     return (<div>{this.props.datatobepassed}</div>)
}
....

答案 2 :(得分:0)

您需要从菜单组件{+ 3}}到拥有&#34;拥有&#34;应用程序组件,然后将其传递给Repos,Followers等。

答案 3 :(得分:0)

您可以通过移动App组件中的状态来实现此目的:

class App extends Component{
    constructor(props){
        super(props);
        this.state = {
            query: ''
        }
    }

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

    render(){
        return(
            <div className="wrapper">
                <Sidebar />
                <div className="main-panel">
                    {* Provide the query value to Menu component *}
                    <Menu onChange={this.handleChange} query={this.state.query} />
                    <div className="content">
                        <div className="container-fluid">
                            <div className="row">
                                {* And provide the same data to Repos component *}
                                <Repos query={this.state.query} />
                                <Followers />
                                <Following />
                                <BirthCount />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

接下来,您可以从Menu组件中删除状态处理:

class Menu extends Component {
    constructor(props){
        super(props);
        this.state = {
        }
    }

    search = () => {
        const BASE_URL = 'https://api.github.com/users/';
        let FETCH_URL = `${BASE_URL}${this.state.query}`;
        console.log('fetchurl', FETCH_URL)

        fetch(FETCH_URL, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(json => {
                const user = json;
                console.log('user json', user);
                this.setState({
                    user
                })
            });
    };

    render(){
        return(
            <div>
                {// providing `onChange` callback and `query` value from props}
                <input onChange={this.props.onChange} value={this.props.query} type="text"/>
                <button onClick={this.search}>submit</button>
            </div>
        )
    }
}

答案 4 :(得分:0)

如果您不使用redux / flux,则需要执行此操作。

class App extends Component{
constructor(props){
   super(props);
     this.state={results:[]};
  this.dataFromSearch=this.dataFromSearch.bind(this);
}
dataFromSearch(data){
this.setState({results:data});
}
render(){
    return(
        <div className="wrapper">
            <Sidebar />
            <div className="main-panel">
                {* In this component the magic happens *}
                {* dataFromSearch will be called when you actually have data 
                   you can pass the same props into the next child of Menu 
                *}
                <Menu callbackFn={this.dataFromSearch} />
                <div className="content">
                    <div className="container-fluid">
                        <div className="row">
                            {* I want to display the data in this component *}
                            <Repos searchData={this.state.results} />
                            <Followers />
                            <Following />
                            <BirthCount />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

}

拥有数据时,在MENU中调用道具方法

class Menu extends Component {
constructor(props){
    super(props);
    this.state = {
    }
}

search = () => {
    const BASE_URL = 'https://api.github.com/users/';
    let FETCH_URL = `${BASE_URL}${this.state.query}`;
    console.log('fetchurl', FETCH_URL)

    fetch(FETCH_URL, {
        method: 'GET'
    })
        .then(response => response.json())
        .then(json => {
            const user = json;
            console.log('user json', user);
            this.setState({
                user
            })  
            // this will call the fn in App and your app state will be 
            //updated
            this.props.callbackFn(user);
        });
}; 

render(){
    return(
        <div>
            {// providing `onChange` callback and `query` value from props}
            <input onChange={this.props.onChange} value={this.props.query} type="text"/>
            <button onClick={this.search}>submit</button>
        </div>
    )
}

}

所以在执行完毕后,您的App状态将拥有数据,并将其作为Props传递给Repo组件。您可以轻松地访问它/