Roblox / roact

A view management library for Roblox Lua similar to React
https://roblox.github.io/roact
Apache License 2.0
563 stars 143 forks source link

Roact should warn when setting state on a component from outside the tree #283

Open oltrep opened 4 years ago

oltrep commented 4 years ago

React does it here.

In Roact, doing this does not provide any useful warnings/errors compared to React.

function Component:init()
    self.props.navigation.setParams({
        headerText = "something"
    })
end
oltrep commented 4 years ago

From the link I put in the previous message, we can translate the test to something similar in Lua:


local Foo = Roact.Component:extend("Foo")
local setValue

function Foo:init()
    setValue = function(newValue)
        self:setState({
            value = newValue,
        })
    end
    self.state = {
        value = "1",
    }
end

function Foo:render()
    return Roact.createElement("TextLabel", {
       Text = self.state.value,
    })
end

local function Bar(props)
    if props.triggerUpdate then
        setValue("3")
    end
    return Roact.createElement("TextLabel", {
        Text = "2",
    })
end

Then if you mount this twice:

local folder = Instance.new("Folder")

local fragment = Roact.createFragment({
    Foo = Roact.createElement(Foo),
    Bar = Roact.createElement(Bar, {triggerUpdate = false}),
})

local handle = Roact.mount(fragment, folder, "Test")

local updatedFragment = Roact.createFragment({
    Foo = Roact.createElement(Foo),
    Bar = Roact.createElement(Bar, {triggerUpdate = true}),
})

Roact.update(handle, updatedFragment)

If you do this in React, you would get this error Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state..

Right now in Roact no warning or error is shown.