【问题标题】:Dropdown Value not passing from one component to the other - React JS下拉值未从一个组件传递到另一个组件 - React JS
【发布时间】:2020-04-07 07:18:18
【问题描述】:

我正在尝试使用 React 中的前端和 Flask 中的后端创建一个 Web 应用程序。我有一个由烧瓶 JSON 填充的下拉列表,它基本上是一个公司列表。总共大约有 5 个组件,第一个是 App.js,第二个是 CompanySelection.js,第三个是 Chart.js 我想返回我的图表和所有内容。

所以在 CompanySelection.js 中,当我更改下拉选择时,更新的公司名称不会进入 Charts.js,即其他组件。我想当这部分得到类似解决时,我可以轻松地将值从一个组件传递到另一个组件。

这是我的三个代码文件:

App.js

import React from "react";
import { CompanyContextProvider } from "./context";
import Dropdown from 'react-dropdown';
import 'react-dropdown/style.css';
import Header from "./Header";
import CompanySelection from "./CompanySelection/CompanySelection.js";
import Charts from "./Charts/Chart.js";
import axios from 'axios';

class App extends React.Component{

    state = {
                companies: [],
                firstCompany: {},
                firstCompanyName: ''
            };


  componentDidMount() {
    fetch('http://127.0.0.1:5001/algo/loc')
    .then(res => res.json())
    .then(data => {
    this.setState({companies: data,
                    firstCompany: data[0],
                    firstCompanyName: data[0].value}, () => 
    console.log(this.state.companies, this.state.firstCompany, this.state.firstCompanyName));
    console.log('')

  }).catch(function (error) {
    console.log(error);
  });
  }

  selectedValueHandler = (selectedValue) => {
    this.setState({
        firstCompanyName: selectedValue
    })
}

  render() {
    const { selectedValue } = this.state.firstCompanyName;
    console.log('change value',selectedValue)
    return (
        <div className="app">
          <Header/> 
          <CompanySelection companies= {this.state.companies} selectedCompany={this.state.firstCompany} setSelectedCompany={this.state.firstCompanyName} selectedValueHandler = {this.selectedValueHandler}/>
          <Charts companies= {this.state.companies} selectedCompany={this.state.firstCompany} setSelectedCompany={selectedValue}/>

        </div>
        );
  }
} ;

export default App;

CompanySelection.js

import { h, render, Component} from 'preact';
import style from './style.css';
import { useContext } from "preact/hooks";
import { CompanyContext } from "../context";

class CompanySelection extends Component {

    constructor(props) 
    { 
        super(props); 
    } 

  render(_, { value }) {

    const companies = this.props.companies;
    const selectedCompany = this.props.selectedCompany; 
    const setSelectedCompany = this.props.setSelectedCompany; 

    var onChange = (e) =>{
        console.log("In on change");
        this.setState({ value: e.target.value });
        const setSelectedCompany = e.target.value;
        console.log("Selected", e.target.value);
        const companies = this.props.companies;
        const selectedCompany = this.props.selectedCompany; 
        this.props.selectedValueHandler(e.target.value);
    }


    if (typeof companies !== 'undefined')
    {
        var options = companies.map((comp) =>
                    <option 
                        key={comp.label}
                        value={comp.value}
                    >
                        {comp.label}
                    </option>
                );
    }
    else {
        var options = [{value: 'A', label: 'B'}].map((comp) =>
                    <option 
                        key={comp.label}
                        value={comp.value}
                    >
                        {comp.label}
                    </option>
                );
    }
    return (
        <fragment class={style.fragment}>
        <label class={style.label}> Company </label>
        <select value={value} onChange={onChange} class={style.dropdown}>
        {options}
        </select>
        </fragment>
    );

  }
}

render(<CompanySelection />, document.body);
export default CompanySelection;

Chart.js

import {  h, render, Component } from 'preact';
import style from './style.css';
import { VictoryChart, VictoryLine, VictoryScatter, VictoryLabel} from 'victory';
import { useContext } from "preact/hooks";
import { CompanyContext } from "../context";

class Charts extends Component {

    constructor(props) 
    { 
        super(props); 
    } 

  render(_, { value }) {
    const companies = this.props.companies;
    const selectedCompany = this.props.selectedCompany; 
    const setSelectedCompany = this.props.setSelectedCompany;
    console.log('list of companies chart', companies)
    console.log('chart input', setSelectedCompany)
    if (typeof selectedCompany !== 'undefined') {
        var comp = selectedCompany;
    }
    else {
        var comp = '';
    }
    console.log("comp", comp);
    return (
        <fragment>
            <div class={style.chart}>
                <VictoryChart domain={[0, 10]}>
                  <VictoryLabel text={comp} x={225} y={30} textAnchor="middle"/>
                  <VictoryLine
                    style={{ data: { stroke: "blue", strokeWidth: 3 } }}
                    y={(d) => d.x}
                  />
                  <VictoryScatter
                    symbol="star"
                    size={8}
                    style={{ data: { fill: "red" }}}
                    data={[{ x: 5, y: 5 }]}
                  />
                  <VictoryScatter
                    symbol="circle"
                    size={8}
                    style={{ data: { fill: "red" }}}
                    data={[{ x: 7, y: 7 }]}
                  />
                </VictoryChart>
            </div>
        </fragment>
    );
  }
}

render(<Charts />, document.body);
export default Charts;

我从这个 stackoverflow 帖子中引用了这段代码:How to pass data from one component to another component in onchange using React js

但是当我看到这行代码的输出时:const { selectedValue } = this.state.firstCompanyName; console.log('change value',selectedValue)

我得到未定义的更改值,这意味着这些值没有被传递。我很新反应,还没有能够解决这个问题。非常感谢任何帮助。

附:组件很好地传递给&lt;CompanySelection..../&gt;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    However when I see the output of this line of code: const { selectedValue } = this.state.firstCompanyName; console.log('change value',selectedValue)

    它将是未定义的,在这里您试图从字符串 firstCompanyName 中解构 selectedValue,只要 this.state.firstCompanyName 不是一个具有名为 selectedValue 的键的对象,它将是未定义的。而是这样做。

        const  selectedValue = this.state.firstCompanyName;
        console.log('change value',selectedValue)`
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2021-01-11
      • 2021-10-31
      • 2018-05-07
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多