HTML JavaScript React:前端 React 组件抛出 react-dom.development.js:506 警告

HTML JavaScript React: Front-End React Component Throwing react-dom.development.js:506 Warning

我已经使用 JSX 语法渲染了一个前端 React/Redux 组件。它执行但在我的控制台中抛出以下警告:

下面是我的代码:

import React from 'react'
import {connect} from 'react-redux'
import {getUsers, deleteUserThunk} from '../store/allUsers'
import {updateUserThunk, fetchSingleUser} from '../store/singleUser'
// Status Filter import BeerFilter from './BeerFilter'
import Card from 'react-bootstrap/Card'
import Button from 'react-bootstrap/Button'
import {UncontrolledCollapse} from 'reactstrap'

export class AllUsers extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      showForm: false,
      stat: ''
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  componentDidMount() {
    try {
      this.props.fetchInitialUsers()
      this.props.deleteUserThunk()
    } catch (error) {
      console.error(error)
    }
  }

  clickHandlerOne() {
    let hidden = this.state.showForm
    this.setState({
      showForm: !hidden
    })
  }

  handleChange(event) {
    //console.log('event.target', event.target)
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  async handleSubmit(userId) {
    event.preventDefault()

    const updatedUser = {
      id: userId,
      isAdmin: this.state.stat
    }

    // console.log('UPDATE USER', updatedUser)

    await this.props.updateUserThunk(updatedUser)
    this.props.fetchInitialUsers()
  }

  render() {
    const users = this.props.users
    // console.log('PROPS', this.props)
    console.log('USERS', this.props.users)

    return (
      <div>
        {/* <div className="options">
          <select onChange={this.handleChange}>
            <option value="">Sort By...</option>
            <option value="priceHighToLow">Price (high to low)</option>
            <option value="priceLowToHigh">Price (low to high)</option>
            <option value="name">Name</option>
          </select>

          <BeerFilter />
          </div> */}

        <div className="flex-cards">
          {users.map(user => (
            <Card style={{width: '18rem'}} key={user.id}>
              {/* delete thunk */}
              <span>
                <p>
                  <Button
                    id={`delete${user.id}`}
                    variant="danger"
                    onClick={() => this.props.deleteUserThunk(user.id)}
                  >
                    X
                  </Button>
                </p>
              </span>

              <Card.Body>
                <Card.Title>User Id: {user.id}</Card.Title>
                <Card.Text>
                  <div>
                    <ul>
                      <li>
                        <div className="highlight">
                          <img src={user.imageUrl} />
                        </div>
                        <div className="details">
                          <p>Username: {user.username}</p>
                          <p>User Email: {user.email}</p>
                          <p>Admin Status: {user.isAdmin ? 'true' : 'false'}</p>
                          <p>
                            Created Date:{' '}
                            {new Intl.DateTimeFormat('en-GB', {
                              month: 'short',
                              day: '2-digit',
                              year: 'numeric'
                            }).format(new Date(user.createdAt))}
                          </p>
                          <p />
                          <Button
                            id={`user${user.id}`}
                            onClick={() => {
                              this.clickHandlerOne()
                            }}
                            variant="outline-info"
                          >
                            Admin Status Toggle
                          </Button>
                          <UncontrolledCollapse toggler={`#user${user.id}`}>
                            {/* {this.state.showForm && (
                              <UpdateUserStatus userId={user.id} />
                            )} */}
                            <form onSubmit={() => this.handleSubmit(user.id)}>
                              <div>
                                <span>
                                  <select
                                    name="stat"
                                    value={
                                      typeof user.isAdmin === 'string'
                                        ? this.state.isAdmin
                                        : user.isAdmin
                                    }
                                    onChange={this.handleChange}
                                  >
                                    <option value="true">true</option>
                                    <option value="false">false</option>
                                  </select>
                                </span>

                                <p />
                                <span>
                                  <p>
                                    {/* */}
                                    <button type="submit">Submit</button>
                                  </p>
                                </span>
                              </div>
                            </form>
                          </UncontrolledCollapse>
                        </div>
                      </li>
                    </ul>
                  </div>
                </Card.Text>
              </Card.Body>
            </Card>
          ))}
        </div>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    users: state.allUsers
  }
}

const mapDispatchToProps = dispatch => {
  return {
    loadSingleUser: id => dispatch(fetchSingleUser(id)),
    updateUserThunk: updatedUser => dispatch(updateUserThunk(updatedUser)),
    //getSortedBeers: (sortBy, beers) => dispatch(sortBeers(sortBy, beers)),
    fetchInitialUsers: () => dispatch(getUsers()),
    deleteUserThunk: userId => dispatch(deleteUserThunk(userId))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AllUsers)

在我的网页中,我(不总是但通常)必须点击编辑按钮两次,我的订单状态才能更新并呈现在我的页面上。我想知道警告是否与此有关。

我做错了什么?我对这种类型的编码非常陌生,因此非常感谢回复的特异性。

<Card.Text> 呈现 <p> 并且您有很多 <div> 嵌套在那里。

我还在 handleSubmit 函数中发现了一个问题。您正在调用 event.preventDefault() 但您没有传递 event 未定义。

除了解决您的控制台错误之外,我还会做一些更改。

  1. this 绑定到 clickHandlerOne
  2. 不要为了采用它们的样式而使用 <p> 标签。示例:

    这对我来说很有意义。这是一段文字。

    <p>Username: {user.username}</p>
    

    这对我来说没有意义。我认为您想要具有特定间距样式的 <button>

    <span>
      <p>
        <Button
          id={`delete${user.id}`}
          variant="danger"
          onClick={() => this.props.deleteUserThunk(user.id)}
        >
          X
        </Button>
      </p>
    </span>
    

试试这段代码,看看它是如何工作的:

import React from "react";
import { connect } from "react-redux";
import { getUsers, deleteUserThunk } from "../store/allUsers";
import { updateUserThunk, fetchSingleUser } from "../store/singleUser";
// Status Filter import BeerFilter from './BeerFilter'
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import { UncontrolledCollapse } from "reactstrap";

export class AllUsers extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showForm: false,
      stat: ""
    };
    this.clickHandlerOne = this.clickHandlerOne.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    try {
      this.props.fetchInitialUsers();
      this.props.deleteUserThunk();
    } catch (error) {
      console.error(error);
    }
  }

  clickHandlerOne() {
    const hidden = this.state.showForm;
    this.setState({
      showForm: !hidden
    });
  }

  handleChange(event) {
    //console.log('event.target', event.target)
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  async handleSubmit(userId) {
    // event.preventDefault(); // I don't think you ave an `event` in scope here

    const updatedUser = {
      id: userId,
      isAdmin: this.state.stat
    };

    // console.log('UPDATE USER', updatedUser)

    await this.props.updateUserThunk(updatedUser);
    this.props.fetchInitialUsers();
  }

  render() {
    const users = this.props.users;
    // console.log('PROPS', this.props)
    console.log("USERS", this.props.users);

    return (
      <div>
        {/* <div className="options">
          <select onChange={this.handleChange}>
            <option value="">Sort By...</option>
            <option value="priceHighToLow">Price (high to low)</option>
            <option value="priceLowToHigh">Price (low to high)</option>
            <option value="name">Name</option>
          </select>

          <BeerFilter />
          </div> */}

        <div className="flex-cards">
          {users.map(user => (
            <Card style={{ width: "18rem" }} key={user.id}>
              {/* delete thunk */}
                <div>
                  <Button
                    id={`delete${user.id}`}
                    variant="danger"
                    onClick={() => this.props.deleteUserThunk(user.id)}
                  >
                    X
                  </Button>
                </div>

              <Card.Body>
                <Card.Title>User Id: {user.id}</Card.Title>
                <Card.Text>
                  <div>
                    <ul>
                      <li>
                        <div className="highlight">
                          <img src={user.imageUrl} />
                        </div>
                        <div className="details">
                          <p>Username: {user.username}</p>
                          <p>User Email: {user.email}</p>
                          <p>Admin Status: {user.isAdmin ? "true" : "false"}</p>
                          <p>
                            Created Date:{" "}
                            {new Intl.DateTimeFormat("en-GB", {
                              month: "short",
                              day: "2-digit",
                              year: "numeric"
                            }).format(new Date(user.createdAt))}
                          </p>
                          <Button
                            id={`user${user.id}`}
                            onClick={() => {
                              this.clickHandlerOne();
                            }}
                            variant="outline-info"
                          >
                            Admin Status Toggle
                          </Button>
                          <UncontrolledCollapse toggler={`#user${user.id}`}>
                            {/* {this.state.showForm && (
                              <UpdateUserStatus userId={user.id} />
                            )} */}
                            <form onSubmit={() => this.handleSubmit(user.id)}>
                              <div>
                                  <select
                                    name="stat"
                                    value={
                                      typeof user.isAdmin === "string"
                                        ? this.state.isAdmin
                                        : user.isAdmin
                                    }
                                    onChange={this.handleChange}
                                  >
                                    <option value="true">true</option>
                                    <option value="false">false</option>
                                  </select>

                                  <div>
                                    {/* */}
                                    <button type="submit">Submit</button>
                                  </div>
                              </div>
                            </form>
                          </UncontrolledCollapse>
                        </div>
                      </li>
                    </ul>
                  </div>
                </Card.Text>
              </Card.Body>
            </Card>
          ))}
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    users: state.allUsers
  };
};

const mapDispatchToProps = dispatch => {
  return {
    loadSingleUser: id => dispatch(fetchSingleUser(id)),
    updateUserThunk: updatedUser => dispatch(updateUserThunk(updatedUser)),
    //getSortedBeers: (sortBy, beers) => dispatch(sortBeers(sortBy, beers)),
    fetchInitialUsers: () => dispatch(getUsers()),
    deleteUserThunk: userId => dispatch(deleteUserThunk(userId))
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AllUsers);

要从 <p> 中获取您所依赖的样式,您可以 inline styles, or use CSS via the className prop.

还有一些 CSS-in-JS 库需要注意,例如 styled-components.

如果这能解决您的问题,请告诉我。