Matt-Esch / virtual-dom

A Virtual DOM and diffing algorithm
MIT License
11.66k stars 779 forks source link

fix: add number verification for children #429

Open ipluser opened 7 years ago

ipluser commented 7 years ago

e.g.

import { h, create } from 'virtual-dom'

const vtree = h('div', [
  h('p', 1),  // the children is number
  h('p', [1]),  // the children is an array that contains number
])

const $rootNode = create(vtree)
document.body.appendChild($rootNode)

`
  <div>
    <p></p>  // not text '1'
    <p>1</p>
  </div>
`

OMG, why not render the first p's text '1'?

next, see the source code:

function h(tagName, properties, children) {
  var childNodes = [];
  var tag, props, key, namespace;

  // children verifycation
  if (!children && isChildren(properties)) {  
    children = properties;
    props = {};
  }

  // ...

  // add childs
  if (children !== undefined && children !== null) {
    addChild(children, childNodes, tag, props);
  }

  return new VNode(tag, props, childNodes, key, namespace);
}

function isChild(x) {
  return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
}

function isChildren(x) {
  // not number verifycation
  return typeof x === 'string' || isArray(x) || isChild(x);
}

function addChild(c, childNodes, tag, props) {
  if (typeof c === 'string') {
    childNodes.push(new VText(c));
  } else if (typeof c === 'number') {  // turns number into VText
    childNodes.push(new VText(String(c)));
  } else if (isChild(c)) {
    childNodes.push(c);
  } else if (isArray(c)) {
    for (var i = 0; i < c.length; i++) {
        addChild(c[i], childNodes, tag, props);  // recursion array's value
    }
  } // ...
}

I think the h('p', 1) and h('p', [1]) must be the same representation:

coveralls commented 7 years ago

Coverage Status

Coverage remained the same at 97.531% when pulling 889118f7ffc1da06ed12a9d7b3e70abaa1e81eb6 on ipluser:master into 947ecf92b67d25bb693a0f625fa8e90c099887d5 on Matt-Esch:master.

coveralls commented 7 years ago

Coverage Status

Coverage remained the same at 97.531% when pulling 8fd0560385a5c4688a546c722717c36d61e1f242 on ipluser:master into 947ecf92b67d25bb693a0f625fa8e90c099887d5 on Matt-Esch:master.