当我在另一个组件中时如何访问状态?

时间:2018-06-05 01:02:30

标签: javascript reactjs state react-props

我是否需要知道如何访问Root组件中的allContent状态,然后显示信息。



import React, {
  Component
} from 'react';
import ContentCards from './ContentCards.js';
import $ from 'jquery';

export class SearchBar extends React.Component {
  constructor(props) 
  {
    super(props);
    this.state = {}
  }

  search(userSearch) 
  {
    console.log('search in action');
    const urlSearch = 'https://api.themoviedb.org/3/search/multi?api_key=16667866c29ba1bc29e687b4892b8d5c&language=en-US&page=1&include_adult=false&query=' + userSearch
    $.ajax({
      url: urlSearch,
      success: (searchs) => {
        console.log('Fetched data succesfully');
        const results = searchs.results;
        var contentSearched = [];

        results.forEach(content => {
          console.log(content);

          content.poster_src = 'https://image.tmdb.org/t/p/w185' + content.poster_path;
          const contents = < ContentCards key = {
            content.id
          }
          content = {
            content
          }
          />
          contentSearched.push(contents);
        });
        this.setState({
          allContent: contentSearched
        });
      },
      error: (xhr, status, err) => {
        console.error('Failed to fetch data');
      }
    });
  }

  searchChangeHandler(event) {
    const userSearch = event.target.value;
    this.search(userSearch);
  }

  render() {
    return ( <
      div className = "navbar-end" >
      <
      div className = "control has-icons-left has-icons-right" >
      <
      input className = "input"
      onChange = {
        this.searchChangeHandler.bind(this)
      }
      placeholder = "search ..." / >
      <
      span className = "icon is-small is-right" >
      <
      i className = "fas fa-search" > < /i> <
      /span> <
      /div> <
      /div>
    );
  }
}
&#13;
&#13;
&#13;

假设Root组件可以访问allContent状态,但我没有成功。具有allContent的功能是能够保存您在其间使用的所有数据,例如,如果用户搜索头像电影,则会显示与所有头像内容相关的表格。

&#13;
&#13;
import React from 'react';
import {NavBar} from './NavBar';

export class Root extends React.Component{
   render(){
      return(
        <div className='container'>
        <div><NavBar/></div>
        <hr/>
        {this.props.allContent}
       </div>
   );
}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

抱歉,我第一次误解了你的问题。

您希望父级能够访问子状态吗?

您必须在根目录中定义子状态并将其作为道具传递下去。 沿着这些方向的东西

class Child extends React.Component
{
  constructor
  {
    this.state = this.props.passedState || {};
    this.upDateState = this.upDateState.bind(this);
  }
  
  updateState(newState)
  {
    //Updates the state of parent, adding child state
    this.props.passToParent(newState);
  }
  
  render()
  {
    return('some stuff')
  }
}

class Parent extends React.Component
{
  constructor()
  {
    this.state = {
      childState : {}.
    }
    this.passToChild = this.passToChild.bind(this);
  }
  
  passToChild(newChildState)
  {
    let currentState = {...this.state};
    currentState.childState = newChildState;
    return this.setState(currentState);
  }
  
  render()
  {
    return(
      <Child
        passState={this.state.childState},
        passToParrent={this.passToChild}
      />
    )
  }
}