【发布时间】:2021-06-25 01:46:43
【问题描述】:
我正在尝试通过在输入中输入用户编号来过滤获取的博客文章。此数字应与帖子 userId 匹配,并仅显示该给定用户“撰写”的帖子(这是一个从 1 到 10 的数字,每个用户有 10 个帖子)。
问题:当我在输入中输入数字时,帖子会消失并且不会过滤任何内容。我很确定我被过滤功能卡住了。
提前致谢!
function App(pst) {
const [posts, setPosts] = useState([]);
const [query, setQuery] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/')
.then(response => response.json())
.then(json => setPosts(json))
}, [])
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Router>
<NavBar />
<Switch>
<Route exact path='/'>
<Home />
<SearchBar
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Grid container spacing={2} justify='center'>
{posts.filter((val) => {
if (query === '') {
return val
} else if (query === val.userId) {
return val
}
console.log(query);
}).map((pst) => (
<PostCard pst={pst} key={pst.id}/>
))}
</Grid>
</Route>
<Route exact path='/singlePost/:postId' component={SinglePost} />
<Route exact path='/PostList'>
<PostList pst={pst}/>
</Route>
</Switch>
</Router>
</ ThemeProvider>
);
}
【问题讨论】:
标签: reactjs filter frontend fetch mapping