简体   繁体   English

如何在 Redux 中制作受控输入组件?

[英]How to make controlled input component in Redux?

I'm implementing movie search functionality using the moviedb api.我正在使用 moviedb api 实现电影搜索功能。 I have implemented in React only but I want to do it in Redux.我只在 React 中实现过,但我想在 Redux 中实现。 Here is my approach in React.这是我在 React 中的方法。

Header.js头文件.js

import React, { Component } from "react"
import { Navbar, Form, FormControl } from "react-bootstrap"
import { NavLink } from "react-router-dom"
import axios from "axios"
import MovieCards from "./MovieCards"
const apiKey = process.env.REACT_APP_MOVIE_DB_API_KEY

class Header extends Component {
  state = {
    isSearching: false,
    value: "",
    movies: []
  }

  searchMovies = async val => {
    this.setState({ isSearching: true })
    const res = await axios.get(
      `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}&page=1&include_adult=true`
    )
    const movies = await res.data.results
    this.setState({ movies: movies, isSearching: false })
  }

  handleChange = e => {
    const { name, value } = e.target
    this.searchMovies(value)
    this.setState({
      [name]: value
    })
  }

  render() {
    return this.state.value === "" ? (
      <div>
        <Navbar
          bg="dark"
          expand="lg"
          style={{ justifyContent: "space-around" }}
        >
          <NavLink to="/">
            <Navbar.Brand>Movie Catalogue</Navbar.Brand>
          </NavLink>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Form inline>
              <FormControl
                type="text"
                placeholder="Search"
                className="mr-sm-2"
                onChange={this.handleChange}
                name="value"
                value={this.state.value}
              />
            </Form>
          </Navbar.Collapse>

          <NavLink to="/popular">Popular</NavLink>
          <NavLink to="/now-playing">Now Playing</NavLink>
          <NavLink to="/top-rated">Top Rated</NavLink>
          <NavLink to="/upcoming">Upcoming</NavLink>
        </Navbar>

        {this.state.movies.map((movie, i) => {
          return <MovieCards key={i} movie={movie} />
        })}
      </div>
    ) : (
      <div>
        <Navbar
          bg="dark"
          expand="lg"
          style={{ justifyContent: "space-around" }}
        >
          <NavLink to="/">
            <Navbar.Brand>Movie Catalogue</Navbar.Brand>
          </NavLink>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Form inline>
              <FormControl
                type="text"
                placeholder="Search"
                className="mr-sm-2"
                onChange={this.handleChange}
                name="value"
                value={this.state.value}
              />
            </Form>
          </Navbar.Collapse>

          <p style={{ color: "white" }}>
            Search results for " {this.state.value} "
          </p>
        </Navbar>

        {this.state.movies.map((movie, i) => {
          return <MovieCards key={i} movie={movie} />
        })}
      </div>
    )
  }
}

export default Header

I want to do it using Redux, so I'm doing it this way.我想用 Redux 来做,所以我是这样做的。

Header.js头文件.js

import React, { Component } from "react"
import { Navbar, Form, FormControl } from "react-bootstrap"
import { NavLink } from "react-router-dom"
import axios from "axios"
import { connect } from "react-redux"
import { movieSearch } from "../actions/index"
import MovieCards from "./MovieCards"
const apiKey = process.env.REACT_APP_MOVIE_DB_API_KEY

class Header extends Component {

  handleChange = e => {
    const { name, value } = e.target
    this.props.dispatch(movieSearch(value)) // I'm not sure if this is the right approach. I'm dispatching and then setting state.
    this.setState({
      [name]: value
    })
  }

  render() {
    return this.state.value === "" ? (
      <div>
        <Navbar
          bg="dark"
          expand="lg"
          style={{ justifyContent: "space-around" }}
        >
          <NavLink to="/">
            <Navbar.Brand>Movie Catalogue</Navbar.Brand>
          </NavLink>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Form inline>
              <FormControl
                type="text"
                placeholder="Search"
                className="mr-sm-2"
                onChange={this.handleChange} 
                name="value" 
                value={this.state.value} 
              />
            </Form>
          </Navbar.Collapse>

          <NavLink to="/popular">Popular</NavLink>
          <NavLink to="/now-playing">Now Playing</NavLink>
          <NavLink to="/top-rated">Top Rated</NavLink>
          <NavLink to="/upcoming">Upcoming</NavLink>
        </Navbar>

        {this.state.movies.map((movie, i) => {
          return <MovieCards key={i} movie={movie} />
        })}
      </div>
    ) : (
      <div>
        <Navbar
          bg="dark"
          expand="lg"
          style={{ justifyContent: "space-around" }}
        >
          <NavLink to="/">
            <Navbar.Brand>Movie Catalogue</Navbar.Brand>
          </NavLink>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Form inline>
              <FormControl
                type="text"
                placeholder="Search"
                className="mr-sm-2"
                onChange={this.handleChange}
                name="value"
                value={this.state.value}
              />
            </Form>
          </Navbar.Collapse>

          <p style={{ color: "white" }}>
            Search results for " {this.state.value} "
          </p>
        </Navbar>

        {this.state.movies.map((movie, i) => {
          return <MovieCards key={i} movie={movie} />
        })}
      </div>
    )
  }
}

const mapStateToProps = (state) => {
   return state
}

export default connect(mapStateToProps)(Header)

actions/index.js动作/ index.js

export const movieSearch = val => {
  const movieSearchUrl = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}&page=1&include_adult=true`

  return async dispatch => {
    dispatch({ type: "SEARCHING_MOVIES_START" })
    try {
      const res = await axios.get(movieSearchUrl)
      dispatch({
        type: "SEARCHING_MOVIES_SUCCESS",
        data: { searchResults: res.data.results }
      })
    } catch (err) {
      dispatch({
        type: "SEARCHING_MOVIES_FAILURE",
        data: { error: "Could not find the movie" }
      })
    }
  }
}

reducers/movieSearchReducer.js减速器/电影搜索Reducer.js

const initialState = {
  value: "",
  isSearchingMovies: false,
  isSearchedMovies: false,
  movieList: [],
  searchingError: null
}

export const movieSearchReducer = (state = initialState, action) => {
  switch (action.type) {
    case "SEARCHING_MOVIES_START":
      return {
        ...state,
        isSearchingMovies: true,
        searchingError: null
      }
    case "SEARCHING_MOVIES_SUCCESS":
      return {
        ...state,
        isSearchingMovies: false,
        isSearchedMovies: true,
        movieList: action.data,
        searchingError: null
      }
    case "SEARCHING_MOVIES_FAILURE":
      return {
        ...state,
        searchingError: action.data.error
      }
  }
}

I'm not sure how to implement the part of the below input form part in Redux.我不确定如何在 Redux 中实现以下输入表单部分的部分。 Please help if you can.如果可以的话请帮忙。

    onChange={this.handleChange}
    name="value"
    value={this.state.value}

When you change from state in component to redux, you will generally remove the react state and pickup the redux state from the 'props'.当您从组件中的状态更改为 redux 时,您通常会删除反应状态并从“道具”中获取 redux 状态。

So step 1 is to get rid of your setState all together.所以第 1 步是一起摆脱你的 setState。

value={this.state.value}值={this.state.value}

will become会变成

value={this.props.movieList}值={this.props.movi​​eList}

In order to get the movieList in the props, you need to wrap your component in a 'container' and use mapStateToProps to map the redux state to your props.为了在 props 中获取 movieList,您需要将组件包装在一个“容器”中,并使用 mapStateToProps 将 redux 状态映射到您的 props。

See https://react-redux.js.org/api/connect for more details有关更多详细信息,请参阅https://react-redux.js.org/api/connect

如果您使用 Redux 存储电影,您可以删除组件的本地状态,并使用 redux 的 movieList 属性代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM