【问题标题】:Selecting random item from Javascript .filter() using React and Mongoose使用 React 和 Mongoose 从 Javascript .filter() 中选择随机项目
【发布时间】:2020-05-20 17:51:41
【问题描述】:

使用 React 和 MongoDB/Mongoose,我试图从数据库中选择一个符合 true 参数的随机项目 - 基本上,用户单击一个按钮来选择一个随机小说或非小说写作提示。现在,当我console.log(fictionPrompts) 时,什么都没有返回,只显示我的 if 函数中的加载片段。我的.filter() 有什么遗漏吗?当我刚刚使用随机器函数从数据库中获取任何提示时,这可以正常工作,而无需尝试过滤特定类型。

来自猫鼬:

const promptSchema = new mongoose.Schema({
  isFiction: {
    type: Boolean,
    required: true
  },
...

部分 React 组件:

const Prompts = props => {
  const [prompts, setPrompts] = useState([])
  const [currentPrompt, setCurrentPrompt] = useState({})

const getFictionPrompts = () => {
    axios(`${apiUrl}/prompts`)
      .then(res => setPrompts(res.data.prompts))
      .then(() => {
        props.alert({
          message: 'You\'ve received a prompt',
          variant: 'success'
        })
      })
      .catch(() => {
        props.alert({
          message: 'Something went wrong',
          variant: 'danger'
        })
      })

    const fictionPrompts = prompts.filter(prompt => (prompt.isFiction === true))
    const newPromptIndex = Math.floor(Math.random() * fictionPrompts.length)
    setCurrentPrompt(fictionPrompts[newPromptIndex])
  }

  let promptsJsx = ''
  if (!currentPrompt) {
    promptsJsx = 'Loading...'
  } else {
    promptsJsx = currentPrompt.text
  }

  return (
    <Layout>
      <button className='btn btn-primary prompt-button' onClick={getFictionPrompts}>Get A Fiction Prompt!</button>
      <button className='btn btn-primary prompt-button' onClick={getNonFictionPrompts}>Get A Non-Fiction Prompt!</button>
      <p>{promptsJsx}</p>
    </Layout>
  )
}

【问题讨论】:

  • 在 setCurrentPrompt 之前,console.log(fictionPrompts[newPromptIndex], newPromptIndex) 会给你什么?
  • @Chad 我在运行时得到undefined 0
  • 这是由于调用的异步性质造成的。

标签: javascript reactjs mongodb mongoose


【解决方案1】:

您在这里遇到问题的原因是,当您尝试设置 currentPrompt 时,axios 仍未返回数据。

如果您将代码更新为以下内容,它应该可以工作:

const getFictionPrompts = () => {
    axios(`${apiUrl}/prompts`)
      .then(res => {
        setPrompts(res.data.prompts);
        // use the data here
        const fictionPrompts = res.data.prompts.filter(
          prompt => prompt.isFiction === true
        );
        const newPromptIndex = Math.floor(
          Math.random() * fictionPrompts.length
        );
        setCurrentPrompt(fictionPrompts[newPromptIndex]);
      })
      .then(() => {
        props.alert({
          message: "You've received a prompt",
          variant: "success"
        });
      })
      .catch(() => {
        props.alert({
          message: "Something went wrong",
          variant: "danger"
        });
      });
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2017-07-01
    相关资源
    最近更新 更多