【问题标题】:Memoize and lodash times get index, create unique text inputsMemoize 和 lodash 时间获取索引,创建唯一的文本输入
【发布时间】:2019-05-17 06:51:20
【问题描述】:

我有一个带有加号的图标按钮。每次单击它时,我都会创建一个文本输入。我简化了示例中的代码,但在我的项目中,我尝试使用它来创建社交图标,在每个文本输入中添加社交图标名称/或 url。代码是 React 中的 JSX:

export default class Test extends Component {
    render() {  

        const { attributes: { totalItems, textInputValue }, setAttributes } = this.props;

        const createItem = memoize( ( totalItems ) => {
            return times( totalItems, () => renderItems( totalItems, textInputValue ) );
        } );

         return (
            <IconButton                 
              label={ __( 'Add text input' ) }
              icon="plus"
              onClick={ () => setAttributes( { totalItems: totalItems + 1 } ) }
            />

            { createItem( totalItems ) }
        )
    }
}

function renderItems( index, textInputValue  ) {
    return (

     <TextControl
        label={ __( 'My text input' ) }
        value={ textInputValue }
        onChange={ ( value ) => setAttributes( { textInputValue: value } ) }
     />  /* how can I get unique text inputs? */

     { index } /* this doesn't return the index of the element created */
    )
}

问题:正在创建相同的文本输入。有没有办法将索引或映射添加到 memoize/times 以呈现唯一输入?

【问题讨论】:

    标签: reactjs lodash jsx memoise


    【解决方案1】:

    Lodash 的 _.times() 将 index 返回到回调:

    const totalItems = 5;
    
    const result = _.times(totalItems, index => ({ index }));
    
    console.log(result);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"&gt;&lt;/script&gt;

    所以在你的情况下,组件应该是这样的:

    注意:我已经删除了 memoize,因为在渲染中多次调用它实际上并没有记忆任何东西。如果你需要 memoize,你应该将函数创建移动到对象的属性中,这样调用就会被缓存。

    export default class Test extends Component {
        render() {  
            const { attributes: { totalItems, textInputValue }, setAttributes } = this.props;
    
            const createItem = (totalItems, textInputValue) =>
              times(totalItems, index => renderItems(index, textInputValue );
    
             return (
                <IconButton                 
                  label={ __( 'Add text input' ) }
                  icon="plus"
                  onClick={ () => setAttributes( { totalItems: totalItems + 1 } ) }
                />
    
                { createItem( totalItems ) }
            )
        }
    }
    

    【讨论】:

    • 谢谢!我现在正在获取索引!我已经更新了我的问题。我不确定如何根据我创建的次数生成具有唯一值的文本输入。
    • 我不太确定您所说的唯一值是什么意思。但是,您可以将索引附加到任何基值,并且它将是唯一的。你也可以使用lodash的_.uniqueId()
    • 这个好像也可以const createItem = () =&gt; times(totalItems, index =&gt; renderItems(index, textInputValue ) )这样用可以吗?
    • 当然。因为你在上下文中有totalItems。当您调用它时,只需调用createItem()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多