如何仅显示结果但在 React JS 中消失按钮

How to show only result but disappear button in React JS

我遇到了一些问题。如果有人帮助,我会很高兴和感激。

  1. 在第一个中,当我单击按钮以显示我通过父组件的道具获得的选项数组时。它显示 options.map 不是函数。但是,在 concole.log() this.state.options 中,通过单击按钮获得道具。我需要的是显示按钮,但是当我单击它时它会消失,并且只显示数组列表。

     import React, { Component } from 'react';
    
     class DoctorSelectTiming extends Component {
       state = {
         options: [],
         isLoading: false
       } 
    
       selectTiming = (props) => {
         const setItems = this.state.options.push(...this.props.props);
         this.setState({options: setItems, isLoading: true});
         console.log(this.state.options );
       }
    
       render() {
         const {isLoading, options } = this.state;
         return (
           <div>
           {!isLoading ? <button onClick={this.selectTiming}>Select Timing</button> : (options.map(option => <li>{option}</li>))
           }
           </div>
               )
       }
     }
    
     export default DoctorSelectTiming;
    

改为在 selectTiming 函数中执行此操作:

selectTiming = () => {
   // set the loading to true first and setting it to false afterwards.
   this.setState({ isLoading: true });
   const newItems = [...this.props.props];
   this.setState({ options: newItems, isLoading: false });
}

您正在分配 this.state.options.push(...this.props.props),理论上,returns 仅分配元素被推入数组后的数组长度。

这是您所做的示例代码:

const arr = [1,2,3,4]
console.log(arr) // [1,2,3,4]
const anotherArr = []
const newArr = anotherArr.push(arr) // assigning it to newArr will only return the length 
                                    // of the array after it was pushed.
console.log(newArr) // 4

因此,更好的方法是为 setItems 分配 this.props.props 的实际值,而不是直接修改实际状态,这是一种糟糕的做法。此外,参数 props 是不必要的,因为 props 已经在您的组件中本地可用。