react-redux - 如何在 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文档。你应该从这个库中导入connect
函数,然后包装你的组件。
function mapStateToProps(state) {
const { todos } = state
return { todoList: todos.allIds }
}
export default connect(mapStateToProps)(TodoList)
更新:
由于您使用的是钩子,因此 useSelector可能对您更有效。
推荐阅读
- excel - Countifs - 单元格引用(整个范围)
- java - 在 Googles AUTOML TABLE 的情况下,如何将“values”属性作为有效负载对象中的字符串数组传递?
- python - 基于带参数的子查询创建注释
- swift - 为什么我无法从开放天气 api 接收任何数据?
- excel - 在电源查询中从文件夹中获取数据时从 .xls 文件中导入数据
- java - Eclipse 在代码完成时抛出异常
- ios - 以编程方式在 UIVisualEffectView 中使用 UITabBarController
- c++ - 如何使用 C++ 更改/设置 DNS?
- python - pytorch hook function is not executed
- node.js - 启动 REACT 前端时 npm 找不到 index.html