如何在没有条件渲染的情况下省略字符串?

时间:2021-04-25 16:09:45

标签: javascript node.js reactjs react-native

singlePost 具有对象形式的数据。我将 singlePost 中的内容呈现为从 1 到 10 的字符串。

然而,内容中随机包含一个空字符串。 Content1 可以包含空或 2 可以包含 8。(即)空字符串随机进入内容。如果传入空字符串,我不想将空内容呈现为文本。

如何修复我的代码?

    const Explain = ({navigation, route}) => {
      const {singlePost} = useSelector((state) => state.post);

      console.log(singlePost);

      // singlePost = {
      //   User: {id: 3, nickname: "bill"},
      //   content1: "number1",
      //   content2: "number2",
      //   content3: "bye",
      //   content4: "empty",
      //   content5: "empty",
      //   content6: "empty",
      //   content7: "empty",
      //   content8: "number3",
      //   content9: "empty",
      //   content10: "empty",
      //   }

      return (
        <Ingretext>
          {singlePost?.content1}
          {'  '}
          {singlePost?.content2}
          {'  '}
          {singlePost?.content3}
          {'  '}
          {singlePost?.content4}
          {'  '}

          {singlePost?.content5}
          {'  '}
          {singlePost?.content6}
          {'  '}
          {singlePost?.content7}
          {'  '}
          {singlePost?.content8}
          {'  '}
          {singlePost?.content9}
          {'  '}
          {singlePost?.content10}
        </Ingretext>
      );
    };

    export default Explain;

2 个答案:

答案 0 :(得分:1)

您可以将 Object.keysArray.prototype.filter 结合使用来实现您的目标。像这样:

['2', '1', '1', '1', '1', '2', '6', '4', '2', '3', '5', '5', '4', '3', '3', '3', '2', '2', '2', '3', '2', '2', '2', '2', '1', '1', '2', '1', '1', '1', '1', '1', '1', '1']

答案 1 :(得分:1)

您也可以使用 reduce 获取非空内容:

let singlePost = {
  User: {
    id: 3,
    nickname: "bill"
  },
  content1: "number1",
  content2: "number2",
  content3: "bye",
  content4: "empty",
  content5: "empty",
  content6: "empty",
  content7: "empty",
  content8: "number3",
  content9: "empty",
  content10: "empty"
};
let contents = Object.keys(singlePost).reduce((acc, key) => {
  if (key.includes("content") && !singlePost[key].includes("empty")) {
    return [...acc, singlePost[key]];
  }
  return acc;
}, []);
console.log(contents);

相关问题