在状态更改时重新渲染功能性 React 组件

时间:2021-06-21 20:08:17

标签: javascript reactjs

我有一个包含多个可能值的表单组。这个选定的值然后作为道具发送到另一个组件,以便它可以在另一个组件中使用。 The problem I am getting is that when another element is selected, the other component doesn't re render with the new prop value.

这是我所指的代码部分:

import OtherComponent from './OtherComponent ';

function Body(){

   
   const [selectedStreet, setSelectedStreet] = useState("11th ave n ganservoort - 12th ave @ 40th st");

   return (
       <div>

           <Form className="mt-5">
               <Form.Group controlId="exampleForm.SelectCustom">
                   <Form.Label>Select Street</Form.Label>
                   <Form.Control as="select" onChange={ (event) =>{
                       setSelectedStreet(event.target.value)
                       // console.log(event.target.value)
                       // console.log(selectedStreet)
                   }} custom>
                       {dataToday.map(s => (
                               <option key={s["street"]} value={s["street"]}>{s["street"]}</option>
                       ))}
                       

                   </Form.Control>
               </Form.Group>
           </Form>
           <OtherComponent streetname={selectedStreet}></OtherComponent >


       </div>


          
   );
}

export default Body;

表单组内的选项只是一个字符串列表。我想知道一旦用户更改了表单组的值,如何能够再次调用该组件。

这是其他组件:


import { Bar, Line, Pie } from 'react-chartjs-2';
import React, { useState } from 'react';

function OtherComponent(props) {

   console.log(props.streetname);

   const [barData, setBarData] = useState({
       labels: ['label 1', 'label 2', 'label 3', 'label 4'],
       datasets: [
           {
               label: props.streetname,
               data: [
                   48,
                   35,
                   73,
                   82
               ],
               backgroundColor: [
                   'rgba(255, 99, 132, 0.6)',
                   'rgba(54, 162, 235, 0.6)',
                   'rgba(255, 206, 86, 0.6)',
                   'rgba(75, 192, 192, 0.6)'
               ],
               borderWidth: 3
           }
       ]
   });

   // set options
   const [barOptions, setBarOptions] = useState({
       options: {
           scales: {
               yAxes: [
                   {
                       ticks: {
                           beginAtZero: true
                       }
                   }
               ]
           },
           title: {
               display: true,
               text: props.streetname,
           },
           legend: {
               display: true,
               position: 'top'
           }
       }
   });

   // return JSX
   return (
       <div className="BarExample">
           <Bar
               data={barData}
               options={barOptions.options} />
       </div>
   );
}


0 个答案:

没有答案