首页 > 解决方案 > 如何在 react redux 中使用 mapStateToProp

问题描述

我正在创建搜索功能,作为我必须用来 mapStateToProps获取数据的请求,我应该在这个文件中做什么?

这是我的代码

import React, { useState, useEffect } from "react";
import useDebounce from "../../custom-hook/index";
import "../Search/index.css";

function Search() {

  // State and setter for search term
  const [searchTerm, setSearchTerm] = useState("");

  // State and setter for search results
  const [results, setResults] = useState([]);

  // State for search status (whether there is a pending API request)
  const [isSearching, setIsSearching] = useState(false);

  // Run every 5ms
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  // Here's where the API call happens
  // We use useEffect since this is an asynchronous action
  useEffect(
    () => {
      // Make sure we have a value (user has entered something in input)
      if (debouncedSearchTerm) {
        // Set isSearching state
        setIsSearching(true);
        // Fire off our API call
        searchCharacters(debouncedSearchTerm).then(results => {
          // Set back to false since request finished
          setIsSearching(false);
          // Set results state
          setResults(results);
        });
      } else {
        setResults([]);
      }
    },
    // This is the useEffect input array
    [debouncedSearchTerm]
  );

  // Pretty standard UI with search input and results
  return (
    <div>
      <input
        placeholder="Search..."
        className="search"
        onChange={e => setSearchTerm(e.target.value)}
      />

      {isSearching && <div>Searching ...</div>}

      {results.map(result => (
        <div key={result.id}>
          <h4>{result.title}</h4>
          <img
            src={`${result.thumbnail.path}/portrait_incredible.${
              result.thumbnail.extension}`}
            alt="something"
          />
        </div>
      ))}
    </div>
  );
}
 // API search function
    function searchCharacters(search) {
      console.log(search);
   }
    
    export default Search;

正如我上面的代码,您可以看到作为回报,我有isSearching功能,它由 useState 设置,但现在我不这样做,我必须设置 mapSateToProp 以从商店获取道具

请帮助我,非常感谢

标签: react-redux

解决方案


这段代码取自react-redux文档。你应该从这个库中导入connect函数,然后包装你的组件。

function mapStateToProps(state) {
  const { todos } = state
  return { todoList: todos.allIds }
}

export default connect(mapStateToProps)(TodoList)

更新:

由于您使用的是钩子,因此 useSelector可能对您更有效。


推荐阅读